简体   繁体   English

Python Tkinter 使用按下按钮的文本创建 label

[英]Python Tkinter create label with text of pressed button

this is my firt post here, hope I´m doing this right, So for my project, I created a set of buttons, and whenever one button is pressed.这是我在这里的第一篇文章,希望我做对了,所以对于我的项目,我创建了一组按钮,并且每当按下一个按钮时。 I want it´s button text to be displayed on a newly created label, Although this seems rather starightforward.我希望它的按钮文本显示在新创建的 label 上,尽管这看起来很简单。 I have quite some difficulties to make it work: Here is the code:我很难让它工作:这是代码:

 a=0
 def label(t):
      nonlocal a
      l = tk.Label(self.parent, text=str(t))
      l.grid(row=1, column=a)
      a += 1

r=0
for components in array:
      button = tk.Button(self.parent, text=str(array[r]), command=lambda: 
      label(array[r]))
      button.grid(row=0, column=r, padx=5, pady=5)
      r+=1

As you can see, I used a for clause to loop over the array to create the buttons.如您所见,我使用 for 子句循环遍历数组以创建按钮。 The problem now is, that the button command assignment seems to be somewhat dynamic (?), meaning, whenever I press any button, it will always display the label text of the last button created, since that´s the current value corresponding to the variable r.现在的问题是,按钮命令分配似乎有些动态(?),这意味着,每当我按下任何按钮时,它总是会显示最后一个按钮创建的 label 文本,因为这是与变量 r。 For example, if the array contains 5 elements A, B, C, D, E, 5 buttons will be created.例如,如果数组包含 5 个元素 A、B、C、D、E,则将创建 5 个按钮。 But when I press any of these, it will always show E.但是当我按下其中任何一个时,它总是会显示 E。

I hope you guys understand my problem and maybe know way to solve it or implement this mechanic in a better way.我希望你们能理解我的问题,也许知道解决它的方法或以更好的方式实现这个机制。 Please not I´m still at the very beginning of programming:)请不要我还处于编程的最开始:)

Thanks and best regards!谢谢和最好的问候!

Try this:尝试这个:

button = tk.Button(self.parent, text=str(array[r]), command=lambda arg=array[r]: label(arg))

This associates the position in the array with the lambda function before it is changed.这会将阵列中的 position 与更改前的 lambda function 相关联。 Let me know if this works for you:)让我知道这是否适合你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM