如何禁用带复选框的小部件?
我想知道怎么用复选框来禁用一个输入框...我试过这个,但它不管用(python 2.7.1)...
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
class Principal(tk.Tk):
def __init__(self, *args, **kwargs):
foo = ""
nac = ""
global ck1
nac = IntVar()
ck1 = Checkbutton(root, text='Test',variable=nac, command=self.naccheck)
ck1.pack()
global ent
ent = Entry(root, width = 20, background = 'white', textvariable = foo, state = DISABLED)
ent.pack()
def naccheck(self):
if nac == 1:
ent.configure(state='disabled')
else:
ent.configure(state='normal')
app=Principal()
root.mainloop()
2 个回答
3
你的代码有很多小问题。首先,Principle
这个类是从 tk.Tk
继承的,但你并没有用 tk
这个名字导入 Tkinter。
其次,你不需要全局变量。你应该使用实例变量来代替。
第三,由于 "nac" 是一个 IntVar
类型的变量,你需要用 get
方法来获取它的值。
最后,你在 textvariable
属性中使用了 foo
作为值,但这只是一个普通的值。它应该是一个 Tk 变量(比如说 StringVar
)。
这里有一个修正过的代码版本:
#!/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()
ck1 = tk.Checkbutton(root, text='Test',variable=self.nac, command=self.naccheck)
ck1.pack()
self.ent = tk.Entry(root, width = 20, background = 'white',
textvariable = self.foo, state = tk.DISABLED)
self.ent.pack()
def naccheck(self):
if self.nac.get() == 1:
self.ent.configure(state='disabled')
else:
self.ent.configure(state='normal')
app=Principal()
root.mainloop()
顺便说一下,使用 from Tkinter import *
还是 import Tkinter as tk
其实是风格问题。我更喜欢后者,因为这样可以明确知道哪个模块包含了类或常量的名称。如果使用 import *
,可能会出现问题,因为你可能会导入一些与文件中其他代码名称冲突的东西。
3
我在Principal类里创建了foo和nac这两个成员变量。
...
self.foo = StringVar()
self.foo.set("test")
self.nac = IntVar()
...
然后在naccheck()函数里引用self.nac。
def naccheck(self):
if self.nac == 1:
ent.configure(state='disabled')
self.nac = 0
else:
ent.configure(state='normal')
self.nac = 1
别忘了把ck1的变量改成self.nac,还有ent的textvariable改成self.foo。
另外,你可能还想把ck1和ent也变成成员变量,因为这样在后面用naccheck()的时候引用它们会更方便。
这些改动在我的Python2.7上运行得很好。