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')
你有两个问题。第一个是您对每一行都使用相同的标记,因此任何对这些行的单击都将触发您所做的最后一个绑定。你知道吗
一个简单的解决方案是为每一行提供一个唯一的标记。例如:
第二个问题是绑定总是使用
i
的最后一个值。您需要创建一个闭包来将循环中的当前值附加到绑定。最常用的方法是通过lambda的默认参数:您不必使用不同的变量名(
item
与i
)。例如,这同样有效:就我个人而言,我发现不熟悉lambdas的人对此感到困惑,所以我喜欢使用不同的名称。你知道吗
相关问题 更多 >
编程相关推荐