【问题标题】:How can I get the button id when it is clicked? [duplicate]单击按钮时如何获取按钮ID? [复制]
【发布时间】:2018-01-25 11:33:23
【问题描述】:

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

我的代码:

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

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

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

【问题讨论】:

  • @EthanField 请不要在问题中添加代码。没有迹象表明 OP 使用python-3.xfiles 的列表。如果不确定,请使用 cmets 进行澄清。
  • OP 已经提供了代码,我让它可以运行,我没有看到任何问题,除了“Tkinter”和“tkinter”之间的区别,代码将在 2.x 中运行或 3.x。此外,OP 声明了for file in files:,这意味着文件是list,所以虽然 OP 没有为我们提供files 的任何数据,但我添加了一个 for 循环,用 OP 声明的 50 个按钮填充它脚本应该添加。我也不同意将这个问题归类为重复问题,这两个问题明显不同
  • @EthanField OP 为文件中的文件声明:意味着文件是一个列表 嗯.. 不。files 可以是任何可迭代的(即生成器、amp 对象、zip对象等),我们不知道它是如何生成的。关于重复.. 链接的问题 exactly 符合 OP 的解释。怎么不重复?

标签: python button tkinter


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢!你真的拯救了我的蟒蛇日! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 2011-05-05
  • 2018-09-24
  • 1970-01-01
相关资源
最近更新 更多