简体   繁体   English

Python Tkinter标题更改从列表

[英]Python Tkinter title change from list

I've tried to simplify the issue with my program through the code below. 我试图通过下面的代码简化程序问题。 I can get it to work but am curious as to why it won't work using the method below. 我可以使它工作,但很好奇为什么不能使用下面的方法。

The print values show the first index, yet the function calls the last index. 打印值显示第一个索引,但是函数调用最后一个索引。

list1 = ["Title_0", "Title_1"]

for i, string in enumerate(list1):
if i == 0:
    print str(i) + ",  " + string # Prints: 0, Title_0
    btn_monty = Button(the_window, text='Monty Python', command = lambda:the_window.title(string))
    #### This also doesn't work ####
    #  btn_monty = Button(the_window, text='Monty Python', command = lambda:the_window.title(list1[i]))

The issue is that the string within the lambda is closed on the variable string , not the value of string . 问题是,该string的拉姆达内封闭的可变string ,而不是值string That means that the value for variable string is not evaluated until the button is actually called, and when it gets called it uses the latest value of string which would be same for both buttons. 这意味着在实际调用按钮之前,不会评估变量string的值,并且在调用按钮时,它将使用string的最新值,这对于两个按钮都是相同的。

You can instead try using default arguments to pass string . 您可以改为尝试使用默认参数传递string Example - 范例-

list1 = ["Title_0", "Title_1"]

for i, strng in enumerate(list1):
    print str(i) + ",  " + strng # Prints: 0, Title_0
    btn_monty = Button(the_window, text='Monty Python', command = lambda new_title=strng:the_window.title(new_title))

I also changed the variable to strng so that it does not conflict with the string module (would be good to avoid any kind of issues in future if you decide to import that module). 我还将该变量更改为strng ,以使其与string模块不冲突(如果您决定导入该模块,最好避免将来出现任何类型的问题)。 Also, you should make sure you place the buttons using grid or pack , etc. 另外,您应该确保使用gridpack等放置按钮。

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

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