单击按钮后如何获取按钮ID? [英] How can I get the button id when it is clicked?

查看:95
本文介绍了单击按钮后如何获取按钮ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何引用tkinter中被单击的按钮.

I don't get how to reference the button being clicked in tkinter.

我的代码:

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

现在例如从作为源的文件中生成了50个按钮.
但是,当我单击任何按钮时,仅引用了LAST按钮,而没有引用我真正要使用/单击的按钮.

Now e.g. 50 buttons are generated from files which is the source.
However when I click any button, only the LAST button is being referenced, but not the button I really want to use/click.

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

In JavaScript we use this to reference the object we really clicked, however I couldn't find any solution in Python for this.

推荐答案

可以使用以下方法完成此操作:

This can be done with something like the below:

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").

So what this does is create a list of buttons, each button has a command assigned to it which is lambda c=i: print(btn[c].cget("text").

让我们分解一下.

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

lambda is used so that the code following isn't executed until the command is called.

我们声明 c = i ,以便将元素 i 作为列表中元素的位置存储在临时且可使用的临时变量 c ,如果我们不这样做,那么该按钮将始终引用列表中的最后一个按钮,因为 i 对应于列表的最后一次运行.

We declare c=i so that the value i which is the position of the element in the list is stored in a temporary and disposable variable c, if we don't do this then the button will always reference the last button in the list as that is what i corresponds to on the last run of the list.

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

.cget("text") is the command used to get the attribute text from a specific tkinter element.

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

The combination of the above will produce the result you want, where each button will print it's own name after being pressed, you can use similar logic to apply it to call whatever attribute or event you need.

这篇关于单击按钮后如何获取按钮ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆