Python Tkinter: Bind function with labels in for loop(Python Tkinter:在for循环中使用标签绑定函数)
问题描述
I'm creating labels dynamically in a for loop using tkinter. I don't know how many labels will be created, but on clicking of each of the labels, a particular function must be called with a particular parameter.
To do this, I'm using this code:
for link in list_of_links:
link_label = Label(self.video_window, text="Frame "+str(video_number), fg="blue", cursor="hand2")
link_label.pack()
link_label.place(x=xcod2, y=ycod2)
link_label.bind("<1>", lambda x: self.goto_video_link(link))
Currently, I'm creating 10 labels. The problem is that on clicking any of the ten labels, the goto_video_link function seems to only use the 10th link.
If I click on the 5th label, I want it to use the 5th link.
How do I go about this?
Lambda expressions are lazily evaluated, which means that self.go_to_link(link) is only evaluated when it is executed. In this moment link contains the value of the last link, so every button will go to the last link.
You need to force the evaluation of link during the for loop. This can be done with a lambda function that returns another lambda function with the value you want. I know it seems confusing, but the code below may make it clearer.
eval_link = lambda x: (lambda p: self.go_to_link(x))
for link in list_of_links:
link_label = Label(self.video_window, text="Frame "+str(video_number), fg="blue", cursor="hand2")
link_label.pack()
link_label.place(x=xcod2, y=ycod2)
link_label.bind("<1>", eval_link(link))
In this case, to be able to build the inner lambda it is necessary to evaluate link. Since it gets passed as a parameter, the inner most lambda is bound to the local copy x instead of link and since x is a local variable, it is always remade when the function is called.
这篇关于Python Tkinter:在for循环中使用标签绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python Tkinter:在for循环中使用标签绑定函数
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
