python - 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!
解决方案
尝试这个:
button = tk.Button(self.parent, text=str(array[r]), command=lambda arg=array[r]: label(arg))
这会将数组中的位置与更改之前的 lambda 函数相关联。让我知道这是否适合你:)
推荐阅读
- python - Selenium 页面内容与 Google Chrome 开发工具不匹配
- c# - C# Entity Framework 删除子表(关系)数据并更新父表
- reactjs - Formik onBlur 触发所有选择组件错误
- ruby-on-rails - Rails 6 将参数更改为哈希值
- javascript - 如何在 Lodash 中修改 groupBy 结果
- debian - 您可以在 .deb 包忙于安装时安装 .deb 包吗?
- java - 如何从不在 Java 项目中的路径打开文件?
- google-chrome - 如何更改 google-chrome 中的快捷方式窗口边框颜色?
- php - Running eloquent in loop and display list in blade based on result from another eloquent query
- flutter - 如何删除 showMenu 周围的空白