for循环中的文本绑定

2024-10-02 20:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

For循环解析文件并将信息添加到字典中。然后在文本小部件中插入一个链接,用户可以单击该链接,然后弹出一个包含字典详细信息的弹出窗口。如果只有一个文件在u中,那么这很好,但是如果有多个文件在u中,那么tag_bind会使用u中的最后一个fle作为popfunc函数。我理解它为什么这样做,但我想不出更好的方法来通过循环,避免这个问题。建议?你知道吗

def popfunc(event, path, dictionary):
    win = Toplevel()
    txt2 = Text()
    txt2.grid()
    for key, value in dictionary.items():
        if path == key:
            txt2.insert('end', value)

txt = Text()
txt.grid()
u = <list of files>
for i in u:
   txt.tag_bind('pop', '<Button-1>', lambda event: popfunc(event, i, dictionary))
   with open(i, 'r') as f:
       h = f.readlines()
       for line in h:
           <parse file and add info to dictionary>       
           txt.insert('end', 'User Info: ')
           txt.insert('end', 'Click here to see info', 'pop')

Tags: 文件pathintxteventfordictionary字典
1条回答
网友
1楼 · 发布于 2024-10-02 20:33:07

你有两个问题。第一个是您对每一行都使用相同的标记,因此任何对这些行的单击都将触发您所做的最后一个绑定。你知道吗

一个简单的解决方案是为每一行提供一个唯一的标记。例如:

for i in u:
    tag = "pop-%s" % i
    ...
    txt.insert('end', 'Click here to see info', tag)

第二个问题是绑定总是使用i的最后一个值。您需要创建一个闭包来将循环中的当前值附加到绑定。最常用的方法是通过lambda的默认参数:

txt.tag_bind('pop', '<Button-1>', lambda event, item=i: popfunc(event, item, dictionary))

您不必使用不同的变量名(itemi)。例如,这同样有效:

txt.tag_bind('pop', '<Button-1>', lambda event, i=i: popfunc(event, i, dictionary))

就我个人而言,我发现不熟悉lambdas的人对此感到困惑,所以我喜欢使用不同的名称。你知道吗

相关问题 更多 >