我正在尝试在for循环中创建相当大的按钮列表,这些按钮也链接到在字典中要调用的相应功能。有一些类似的帖子here和here讨论了使用lambda分配name = name的问题,但是我似乎无法弄清楚如何将其合并到这个特定的实例中,每个实例都调用一个不同的函数。字典,而不是更改单个函数的单个参数。这是一个例子。
import tkinter as tkinter
root = tkinter.Tk()
def funct1():
print("Printed Func1")
def funct2():
print("Printed Func2")
buttons_dict = {"button1": "Func1", "button2": "Func2"}
row = 0
for name in buttons_dict:
buttons = tkinter.Button(root, text=name) # command=lambda name=name: root(name))
buttons.grid(row=row)
buttons.config()
row += 1
root.mainloop()
从这样的字典中收集信息时,将名称分配给函数的正确方法是什么?
答案 0 :(得分:4)
您可以像这样在字典中引用该函数:
import tkinter as tkinter
root = tkinter.Tk()
def funct1():
print("Printed Func1")
def funct2():
print("Printed Func2")
buttons_dict = {"button1": funct1, "button2": funct2}
row = 0
for name in buttons_dict:
buttons = tkinter.Button(root, text=name, command=buttons_dict[name])
buttons.grid(row=row)
buttons.config()
row += 1
root.mainloop()