首页 > 解决方案 > 删除超类的部分方法

问题描述

我目前正在学习继承和覆盖方法。我能够添加到某个方法,但现在我正在努力从超类的方法中删除一些东西。更具体地说,我的超类是来自 tkinter 的 simpledialog 的 Dialog 类。我想更改子类中的 buttonbox() 方法,以便隐藏或删除取消按钮。我将展示 Dialog 超类的“ init ”方法和 buttonbox 方法:

class Dialog(Toplevel):

    def __init__(self, parent, title = None):
        Toplevel.__init__(self, parent)
        self.withdraw() 
        if parent.winfo_viewable():
            self.transient(parent)
        if title:
            self.title(title)
        self.parent = parent
        self.result = None
        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.buttonbox()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        if self.parent is not None:
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                  parent.winfo_rooty()+50))
        self.deiconify() # become visible now
        self.initial_focus.focus_set()
        self.wait_visibility()
        self.grab_set()
        self.wait_window(self)

    def buttonbox(self):
        box = Frame(self)
        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)
        box.pack()

所以现在在创建我的子类时,我想继承超类但重写按钮框方法,这样我就只有一个按钮(带有 OK 的按钮)。

MyDialogClass(simpledialog.Dialog):
    def buttonbox(self):
        #code that will override the buttonbox method of superclass       

我如何覆盖这个?

标签: python-3.xtkinterdialog

解决方案


Welp,我试过了,我想我有一个解决方案,我现在觉得有点愚蠢。

MyDialogClass(simpledialog.Dialog):
    def buttonbox(self):
        box = tkinter.Frame(self)
        w = tkinter.Button(box, text="OK", width=10, command=self.ok, default="active")
        w.pack(side="left", padx=5, pady=5)
        self.bind("<Return>", self.ok)
        box.pack()

一开始我的主要问题是,我在使用“box = Frame(self)”时遇到了 NameError,就像 Superclass buttonbox 方法一样。现在我使用了 tkinter.Frame(self) 它工作了。


推荐阅读