Python 使用按钮小部件在Tkinter中正确使用继承
我正在Tkinter中使用Python 2.11编写一个GUI,使用OOP方法,并尝试学习继承。我编写了一个名为ButtonField的子类,它继承自tk.Button。在ButtonField中,我有一个名为pressMe的方法,它可以在按下按钮时更改按钮的颜色和文本 我的最终目标是在GUI中有更多的按钮,以及ButtonField类中包含的所有相关方法,以获得更干净、更易于管理的代码 当我按下按钮时,屏幕上会显示文本“In press Me Method”,因此该方法可能正在工作,但按钮小部件不会更改文本或背景颜色Python 使用按钮小部件在Tkinter中正确使用继承,python,oop,tkinter,Python,Oop,Tkinter,我正在Tkinter中使用Python 2.11编写一个GUI,使用OOP方法,并尝试学习继承。我编写了一个名为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()
考虑这一行代码:
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)
对于特定的bug,您有一个很好的答案,但是,您计划对所有内容使用继承,这不是一个好主意,而且会使代码比原来更复杂。除非您正在制作全新的小部件,否则只需使用组合和委派,您将在大多数tkinter示例中看到这一点。