cyt*_*zix 3 python tkinter button
我不知道如何引用在 tkinter 中单击的按钮。
我的代码:
for file in files:
btn = Button(root, text=file).pack()
Run Code Online (Sandbox Code Playgroud)
现在例如 50 个按钮是从作为源的文件生成的。
但是,当我单击任何按钮时,只会引用最后一个按钮,而不是我真正想要使用/单击的按钮。
在 JavaScript 中,我们使用this引用我们真正点击的对象,但是我在 Python 中找不到任何解决方案。
这可以通过如下方式完成:
from tkinter import *
root = Tk()
files = [] #creates list to replace your actual inputs for troubleshooting purposes
btn = [] #creates list to store the buttons ins
for i in range(50): #this just popultes a list as a replacement for your actual inputs for troubleshooting purposes
files.append("Button"+str(i))
for i in range(len(files)): #this says for *counter* in *however many elements there are in the list files*
#the below line creates a button and stores it in an array we can call later, it will print the value of it's own text by referencing itself from the list that the buttons are stored in
btn.append(Button(root, text=files[i], command=lambda c=i: print(btn[c].cget("text"))))
btn[i].pack() #this packs the buttons
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
所以它的作用是创建一个按钮列表,每个按钮都有一个分配给它的命令,即lambda c=i: print(btn[c].cget("text").
让我们分解一下。
lambda 使用,以便在调用命令之前不会执行以下代码。
我们声明,作为元素在列表中的位置c=i的值i存储在一个临时和一次性变量中c,如果我们不这样做,那么按钮将始终引用列表中的最后一个按钮,因为它i对应于在列表的最后一次运行中。
.cget("text")是用于text从特定 tkinter 元素获取属性的命令。
以上组合将产生您想要的结果,其中每个按钮在按下后都会打印自己的名称,您可以使用类似的逻辑应用它来调用您需要的任何属性或事件。
| 归档时间: |
|
| 查看次数: |
7716 次 |
| 最近记录: |