当您看到该窗口时,integer 已不存在,并且该复选框显示为未选中,因为缺少用于存储其状态的变量。
比较:
from tkinter import *
root = Tk()
def main():
global integer
integer = IntVar(value=1)
Checkbutton(root, text="Should be on by default", variable=integer).grid()
main()
root.mainloop()
global integer 告诉 Python 这个integer 应该在“全局”级别定义,因此它会保留在函数之后。
顺便说一句,根据变量的类型命名变量是不好的做法 - 尝试选择一个代表其值含义的名称,而不是描述其类型。
您分享了一些具有类似问题的附加代码(仅重复重要的元素):
from tkinter import *
def change_job_skills(name):
top_window = Toplevel(root)
# ..
skill_dictionary = {}
# ..
row_ = 2
column_ = 0
# ..
job_focuses_dictionary = {}
for key in sorted(job_focuses_dictionary.keys()):
Checkbutton(top_window, text=key.strip(""),
variable=job_focuses_dictionary[key]).grid(row=row_, column=column_, sticky=W)
# ..
# no definition was provided of actually_change_job_skills, but it's not important here
Button(top_window, text='Submit',
command=lambda: [actually_change_job_skills(skill_dictionary, name),
top_window.destroy()]).grid(row=0, column=0, sticky=W)
# no reference is made to `job_focuses_dictionary` in a way that survives the function
root = Tk()
change_job_skills("Community Engagement")
root.mainloop()
虽然skill_dictionary 和job_focuses_dictionary 都在change_job_skills 的代码中使用,但skill_dictionary 用于定义lambda 函数,然后作为command 参数传递给Button。由于按钮稍后需要调用该函数,因此在其中保存了对 lambda 的引用,并且由于 lambda 的函数体引用了skill_dictionary,因此字典在函数返回时仍然存在。
但是,job_focuses_dictionary 仅被引用为 job_focuses_dictionary[key],从中检索一个值 - 字典本身不会传递给在函数外部维护对它的引用的任何东西,所以当函数返回时,字典是垃圾收集。
同样的问题,但更难发现。 (@acw1668 在 cmets 中也指出了这一点)
请注意,我还将您的参数 Name 重命名为 name,您应该为类型保留大写名称,为变量保留小写名称,符合 Python 标准命名,这有助于您和其他人更快地阅读和理解您的代码。不过与问题无关。