简体   繁体   English

Python Tkinter:在for循环中将带有标签的函数绑定

[英]Python Tkinter: Bind function with labels in for loop

I'm creating labels dynamically in a for loop using tkinter . 我正在使用tkinterfor loop动态创建标签。 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. 目前,我正在创建10个标签。 The problem is that on clicking any of the ten labels, the goto_video_link function seems to only use the 10th link. 问题在于,单击十个标签中的任何一个, goto_video_link函数似乎仅使用第十个链接。

If I click on the 5th label, I want it to use the 5th link. 如果单击第5个标签,则希望它使用第5个链接。

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. Lambda表达式是延迟计算的,这意味着self.go_to_link(link)仅在执行时才计算。 In this moment link contains the value of the last link, so every button will go to the last link. 此时, link包含最后一个链接的值,因此每个按钮都将转到最后一个链接。

You need to force the evaluation of link during the for loop. 您需要在for循环中强制评估link This can be done with a lambda function that returns another lambda function with the value you want. 这可以通过lambda函数完成,该函数返回另一个具有所需值的lambda函数。 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 . 在这种情况下,要能够构建内部lambda,必须评估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. 由于将其作为参数传递,因此最里面的lambda绑定到本地副本x而不是link并且由于x是本地变量,因此在调用函数时始终会对其进行重新制作。

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

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