创建带有tkinter的按钮.如何知道点击了哪个?



我创建了一个命令,它读取文本文件中的元素,并为该文本文件中的每个元素创建一个按钮。

for element in myfile:
button=Button(root, text="hi").pack()

我想分配给每个按钮一个特定的值(就像如果我按下一个特定的按钮会出现的东西),但我得到相同的命令每个按钮…我该怎么做呢?

我不知道你在链接的答案中有什么不明白的。下面是两个可用的示例。

import tkinter as tk
root = tk.Tk()
label = tk.Label( root, text = ' Nothing Clicked Yet ')
def button_cmd( obj ):
label.config( text = obj.cget("text" ) + " clicked." ) 
for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
button = tk.Button( root, text = caption )  # Create the button object

button.config( command = lambda obj = button:  button_cmd( obj ) )
# Configure the command option. This must be done after the button is 
# created or button will be the previous button. 

button.pack()
label.pack()
root.mainloop()

不使用lambda创建闭包的另一种方法。

root = tk.Tk()
label = tk.Label( root, text = ' Nothing Clicked Yet ')
def make_button_cmd( obj ): 
# This returns a function bound to the obj
def func():
label.config( text = obj.cget("text" ) + " clicked." ) 
return func
for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
button = tk.Button( root, text = caption )  # Create the button object

button.config( command = make_button_cmd( button ) )
# Configure the command option. This must be done after the button is 
# created or button will be the previous button. 

button.pack()
label.pack()
root.mainloop()

最新更新