首页 > 解决方案 > 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, 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. 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. For example, if the array contains 5 elements A, B, C, D, E, 5 buttons will be created. But when I press any of these, it will always show 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!

标签: pythonbuttontkinterlabel

解决方案


尝试这个:

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

这会将数组中的位置与更改之前的 lambda 函数相关联。让我知道这是否适合你:)


推荐阅读