python - 用 tkinter 和 for.. 创建按钮如何知道点击了哪一个?
问题描述
我创建了一个命令,它读取文本文件的元素,并为该文本文件中的每个元素创建一个按钮。
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()
推荐阅读
- apache-nifi - Apache Nifi - 使用 API 创建新管道
- ruby-on-rails - 如果用户在不到 2 天内发布,如何防止发布?
- html - 如何使用'xpath'在html中提取我想要的东西
- mongodb - .populate 不适用于猫鼬 5.2
- python - ValueError:使用序列numpy设置数组元素
- python - 如何在我的词汇表中为 CountVectorizer 使用正则表达式?
- android - 列数更改时为 Recycler View 网格设置动画
- r - 有什么方法可以在不更改数据的情况下在 ggplot 中选择 x 轴上的值标签?
- if-statement - Android if 语句在 setOnClickListener 上不起作用
- xml - 如何同时更改多个 XML 属性