【发布时间】: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 示例中看到的组合和委托。