问题描述
我正在使用tkinter
在for loop
中动态创建标签.我不知道将创建多少个标签,但是在单击每个标签时,必须使用特定的参数来调用特定的函数.
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))
当前,我正在创建10个标签.问题在于,单击十个标签中的任何一个,goto_video_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.
如果我点击第5个标签,则希望它使用第5个链接.
If I click on the 5th label, I want it to use the 5th link.
我该怎么办?
推荐答案
Lambda表达式是延迟计算的,这意味着self.go_to_link(link)
仅在执行时才计算.此时,link
包含最后一个链接的值,因此每个按钮都将转到最后一个链接.
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.
您需要在for循环中强制执行link
的求值.这可以通过lambda函数完成,该函数返回另一个具有所需值的lambda函数.我知道这似乎令人困惑,但是下面的代码可能会使它更清晰.
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))
在这种情况下,要能够构建内部lambda,必须评估link
.由于将其作为参数传递,所以最里面的lambda绑定到本地副本x
而不是link
,并且由于x
是本地变量,因此在调用函数时始终会对其进行重制.
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循环中将带有标签的函数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!