使用 Button 小部件在 Tkinter 中正确使用继承

Posted

技术标签:

【中文标题】使用 Button 小部件在 Tkinter 中正确使用继承【英文标题】:Proper Use Of Inheritance in Tkinter using Button widget 【发布时间】:2017-07-08 03:55:57 【问题描述】:

我正在使用 Python 2.11 使用 OOP 方法在 Tkinter 中编写 GUI,并尝试学习继承。我编写了一个名为 ButtonField 的子类,它继承自 tk.Button。在 ButtonField 中,我有一个名为 pressMe 的方法,它在按下时会更改按钮的颜色和文本。

我的最终目标是在 GUI 中拥有更多按钮以及 ButtonField 类中包含的所有相关方法,以实现更简洁、更易于管理的代码。

当我按下按钮时,屏幕上会显示文本“In Press Me Method”,因此该方法可能正在工作,但按钮小部件不会更改文本或背景颜色。

import Tkinter as tk

class MainWindow(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.olFrame = tk.LabelFrame(text = 'Initial Frame', bg = 'grey')
        self.olFrame.grid(column = 0, row = 0, sticky = 'w')

        self.simpleButton = ButtonField(self.olFrame, text = "Press Me",bg= "green"
                                     ,command = ButtonField(self).pressMe)
        self.simpleButton.grid(column = 0, row = 0)

class ButtonField(tk.Button):
    def __init__(self, parent, *args, **kwargs):
        tk.Button.__init__(self, parent, *args, **kwargs)
        self.parent = parent

    def pressMe(self):
        print "In Press Me Method"
        self.configure(text = "Pressed Now", background = "yellow")
        #self.parent.configure(self, text = "Pressed Now", background = "yellow")  #returns TclError: unknow option "-text"

root = tk.Tk()
root.geometry('500x400')
root.title('Test GUI')
root.configure(background = "black")

a = MainWindow(root)
root.mainloop()

【问题讨论】:

您对特定错误有一个很好的答案,但是您计划对所有内容使用继承并不是一个好主意,并且会使您的代码比现在更复杂。除非您正在制作全新的小部件,否则只需使用您将在大多数 tkinter 示例中看到的组合和委托。 【参考方案1】:

考虑这行代码:

self.simpleButton = ButtonField(..., command = ButtonField(self).pressMe)

这和你这样做完全一样:

another_button = Button(self)
self.simpleButton = ButtonField(..., command=another_button.pressMe)

因为您正在调用另一个不可见按钮的功能,所以您看不到更改。如果您希望按钮调用自己的功能,您需要分两步完成:

self.simpleButton = ButtonField(...)
self.simpleButton.configure(command=self.simpleButton.pressMe)

【讨论】:

以上是关于使用 Button 小部件在 Tkinter 中正确使用继承的主要内容,如果未能解决你的问题,请参考以下文章

python Tkinter之Button

tkinter 中的框架对象没有对小部件进行分组

如何在粘性框架中居中 tkinter 小部件

限制Tkinter Entry小部件中的值

重置Tkinter窗口,还原小部件

如何将回车键绑定到tkinter中的函数?