【发布时间】:2015-12-07 06:45:38
【问题描述】:
我正在 python 2,7 中使用 Tkinter 编写一个小 gui。在某些时候,我调用了一个函数来创建一个由多个复选框填充的弹出窗口,复选框的数量由属性变量定义。
def attribute_select(attributes):
popup = tk.Tk()
popup.wm_title("Attribute selection")
label = ttk.Label(popup, text="Please select which of the following \n attributes will undergo k-anonymity.",
font=NORMAL_FONT)
label.pack(side="top", fill="x", pady=10)
def read_status(key):
var_obj = var.get(key)
print "key is:", key
print "var_obj.get() is:", var_obj.get()
def leave_mini():
popup.destroy()
var = dict()
count = 1
for child in range(attributes):
var[child] = tk.IntVar()
chk = tk.Checkbutton(popup, text='Attribute: '+str(count), variable=var[child], justify="left", onvalue=1,
offvalue=0, command=lambda key=child: read_status(key))
count += 1
chk.pack()
print var
exit_button = ttk.Button(popup, text="OK", command=leave_mini)
exit_button.pack()
popup.mainloop()
一切运行良好,但是当我尝试检查其中一个框时,变量值不会每次都更改打印输出:[ key is: 0 var_obj.get() is: 0 ] 或 [ key is: 5 var_obj.get() 是:0]。因此,密钥适用于每个框,但变量不会改变。我确定这是一个简单的修复,我只是看不到它...有什么想法吗?
【问题讨论】:
-
您在程序中使用其他 tkinter 窗口吗?它应该只有一个
mainloop()和一个tk.Tk()- 对于子窗口使用tk.Toplevel()。 -
发布的代码不会运行。阅读stackoverflow.com/help/mcve
-
谢谢你,这是我第一次使用 tkinter,我完全没有想到 mainloop 问题。