我正在学习在Python 3.6.4中使用tkinter。 我正在创建一个带有多个按钮实例的 GUI。 两个这样的实例是:
def createWidgets(self):
# first button
self.QUIT = Button(self)
self.QUIT["text"] = "Quit"
self.QUIT["command"] = self.quit
self.QUIT.pack()
# second button
self.Reset = Button(self)
self.Reset["text"] = "Reset"
self.Reset["command"] = "some other function, tbd"
我想学习的是如何抽象按钮的实例化,以便 createWidgets 方法中的每个实例都基于如下方法:
createButton( self, text, command, fg, bg, hgt, wth, cursor ):
我不知道的是如何将按钮的命名控制为:
self.QUIT
self.Reset
其中,"." 运算符后面的属性或名称可以作为创建和命名按钮的属性传递给 createButton。
简单地扩展 Brian 所说的内容,这段代码就会让你继续前进。按钮对象存储在小部件字典中。这是将其组合在一起的一种方法:
import tkinter as tk
import sys
root = tk.Tk()
class CustomButton(tk.Button):
def __init__(self, parent, **kwargs):
tk.Button.__init__(self, parent)
for attribute,value in kwargs.items():
try:
self[attribute] = value
except:
raise
def doReset():
print("doRest not yet implemented")
if __name__ == '__main__':
widget = {}
widget['quit'] = CustomButton(root, text='Quit', command=sys.exit)
widget['reset'] = CustomButton(root, text='Reset', command=doReset)
for button in widget.keys():
widget[button].pack()
root.mainloop()