所以我有这段代码,并希望按钮在被单击时返回其文本值。
film = ['Woezel & Pip Op zoek naar de Sloddervos!', 'The White Snake',
'Proof of Life', 'Rise of the Planet of the Apes',
'Mona Lisa Smile', '2 Guns', 'Max Payne', 'De eetclub']
for item in film:
button = Button(master=aanbiederspage, text=item,
command=filmdatabase).pack()
最佳答案
执行此操作的简单方法是将 item
字符串传递给 command
回调,但您必须小心执行此操作的方式。一种方法是使 item
字符串成为 lambda
函数的默认参数。它必须是默认参数,以便在定义 lambda 时将 item
绑定(bind)到该参数。如果我们只是执行 lambda : func(item) ,那么每个按钮都会打印列表中的最后一项。发生这种情况是因为在这种情况下,当调用回调时,Python 会查找 item
的当前值。
import tkinter as tk
film = ['Woezel & Pip Op zoek naar de Sloddervos!', 'The White Snake',
'Proof of Life', 'Rise of the Planet of the Apes', 'Mona Lisa Smile',
'2 Guns', 'Max Payne', 'De eetclub']
def func(item):
print(item)
root = tk.Tk()
for item in film:
tk.Button(master=root, text=item, command=lambda s=item: func(s)).pack()
root.mainloop()
请注意,在我的代码中,我不执行 button = tk.Button(
... 进行该分配是没有意义的。首先,我们不保存这些小部件在任何地方,但更重要的是,.pack
返回 None
,所以这样做
button = Button(master=aanbiederspage, text=item, command=filmdatabase).pack()
实际上将 button
设置为 None
,而不是 Button 小部件。
关于python - 如何让 tkinter 按钮返回其文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916958/