【发布时间】:2013-02-12 13:02:53
【问题描述】:
在 Python 2.7 中,我想通过一个检查按钮将“条目”小部件的状态变为正常/禁用。
借助这个问题Disable widget with checkbutton?,我可以用 1 个复选按钮和 1 个条目来完成
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import Tkinter as tk
root = tk.Tk()
class Principal(tk.Tk):
def __init__(self, *args, **kwargs):
self.foo = tk.StringVar()
self.nac = tk.IntVar()
self.ck1 = tk.Checkbutton(root, text='test',
variable=self.nac, command=self.naccheck)
self.ck1.pack()
self.ent1 = tk.Entry(root, width=20, background='white',
textvariable=self.foo, state='disabled')
self.ent1.pack()
def naccheck(self):
print "check"
if self.nac.get() == 0:
self.ent1.configure(state='disabled')
else:
self.ent1.configure(state='normal')
app = Principal()
root.mainloop()
当我想要 2 对或更多对(检查按钮/条目)时,问题就来了。 在我的最终界面中,我可能有 20 个或更多这对,所以我想避免有 20 个或更多相同的“naccheck”方法。
我试过了:
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import Tkinter as tk
root = tk.Tk()
class Principal(tk.Tk):
def __init__(self, *args, **kwargs):
self.foo = tk.StringVar()
self.nac = {}
self.ent = {}
self.ent["test"] = tk.Entry(root, width=20, background='white', textvariable=self.foo, state='disabled')
self.ent["test"].pack()
self.ent["image"] = tk.Entry(root, width=20, background='white', textvariable=self.foo, state='disabled')
self.ent["image"].pack()
self.nac["test"] = tk.IntVar()
self.ck1 = tk.Checkbutton(root, text='test', variable=self.nac["test"], command=self.naccheck("test"))
self.ck1.pack()
self.nac["image"] = tk.IntVar()
self.ck1 = tk.Checkbutton(root, text='image', variable=self.nac["image"], command=self.naccheck("image"))
self.ck1.pack()
def naccheck(self,item):
print "check "+item
print self.nac[item].get()
if self.nac[item].get() == 0:
self.ent[item].configure(state='disabled')
else:
self.ent[item].configure(state='normal')
app = Principal()
root.mainloop()
不幸的是,当我启动此代码时,会立即为每个检查按钮调用“naccheck”方法,而当我单击一个按钮时,则永远不会...
我做错了什么?
【问题讨论】:
-
为什么不将所有
Entrys 存储在一个数组中,然后在naccheck中对它们运行for循环? -
我的条目在一个数组中! 1个检查按钮必须“激活”相关条目。循环遍历 Entry 有什么好处?
标签: python checkbox tkinter tkinter-entry