2017-08-17 175 views
0

我不明白如何引用在tkinter中点击的按钮。点击时如何获得按钮ID?

我的代码:

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

现在如从源文件生成50个按钮。
但是,当我点击任何按钮,只有最后一个按钮被引用,但不是我真正想要使用/点击的按钮。

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

+1

@EthanField请不要添加代码的问题。没有迹象表明OP使用[tag:python-3.x]或'files'列表。如果您不确定,请使用评论来澄清。 – Lafexlos

+0

OP已经提供了代码,我使它可以运行,除了“Tkinter”和“tkinter”之间的代码将在2.x或3.x中运行之间的区别之外,我没有看到任何问题。另外,OP声明'用于文件中的文件:'表示文件是一个'list',所以虽然OP没有向我们提供任何'files'的数据,但我添加了一个for循环来使用50个按钮来填充它OP表示应该添加脚本。我也不同意这个问题的分类是重复的,这两个问题显然是不同的 –

+0

@EthanField _OP声明文件中的文件:这意味着这个文件是一个list_umm ..号.'文件'可以是任何可迭代的(即发电机,放大器对象,拉链对象等),我们不知道它是如何产生的。关于重复..链接的问题_exactly_做OP解释。它如何不重复? – Lafexlos

回答

0

这可以像下面这样做:

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的命令。

上面的组合会产生你想要的结果,每个按钮在被按下后会打印它自己的名字,你可以使用类似的逻辑来应用它来调用你需要的任何属性或事件。

+0

非常感谢!你真的救了我的蟒蛇日! :) – cytzix

相关问题