如何点击按钮ID?

时间:2017-08-17 07:02:42

标签: python button tkinter

我不知道如何引用在tkinter中单击的按钮。

我的代码:

for file in files: 
     btn = Button(root, text=file).pack()

现在,例如从作为源的文件生成50个按钮 但是,当我单击任何按钮时,只会引用最后一个按钮,而不是我真正想要使用/单击的按钮。

在JavaScript中,我们使用this来引用我们真正点击的对象,但是我在Python中找不到任何解决方案。

1 个答案:

答案 0 :(得分:2)

这可以通过以下方式完成:

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()

所以这样做是创建一个按钮列表,每个按钮都有一个分配给它的命令lambda c=i: print(btn[c].cget("text")

让我们打破这一点。

使用

lambda以便在调用命令之前不执行以下代码。

我们声明c=i,以便作为列表中元素位置的值i存储在临时和一次性变量c中,如果我们不这样做的话执行此操作然后按钮将始终引用列表中的最后一个按钮,因为i对应于列表的最后一次运行。

.cget("text")是用于从特定tkinter元素获取属性text的命令。

上述组合将产生您想要的结果,每个按钮在按下后将打印出自己的名称,您可以使用类似的逻辑将其应用于调用您需要的任何属性或事件。