我尝试将字典传递给模拟和 tkinter 的 Button 类 init 函数。我注意到一个区别:使用模拟 = True(我自己的 Button 类),我必须作为关键字参数传入 **dict,但是使用 tkinter 的 Button 类(模拟 = False),我可以带或不带 ** 传入。有什么解释吗?
simulation = True
dictA = dict(text="Print my name with button click", command=lambda: print("My name is here"), fg="blue")
dictB = dict(text="Print your name with button click", command=lambda: print("Your name is there"),
fg="white", bg="black")
if simulation == False:
import tkinter as tk
root = tk.Tk()
dict = [dictA, dictB]
for d in dict:
# btn = tk.Button(root, d) # This works too!?
btn = tk.Button(root, **d)
btn.pack()
root.mainloop()
else:
class Button:
def __init__(self, **kwArgs):
if (kwArgs.get('text') == None):
self.text = "button"
else:
self.text = kwArgs['text']
if (kwArgs.get('command') == None):
self.command = lambda arg: print(arg)
else:
self.command = kwArgs['command']
if (kwArgs.get('fg') == None):
self.fg = "black"
else:
self.fg = kwArgs['fg']
if (kwArgs.get('bg') == None):
self.bg = "white"
else:
self.bg = kwArgs['bg']
print("text = {0}, command inline function = {1}, fg color = {2}, bg color = {3}".
format(self.text, self.command, self.fg, self.bg))
btnDefault = Button()
btnDictA = Button(**dictA)
btnDictB = Button(**dictB)