如何使用复选按钮禁用条目。。。我有这个,但它不起作用(Python2.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()
你的代码有很多小问题。首先,
Principle
从tk.Tk
继承,但不以tk
名称导入Tkinter。其次,不需要全局变量。您应该改用实例变量。
第三,因为“nac”是一个
IntVar
,所以需要使用get
方法来获取值。最后,使用
foo
作为textvariable
属性的值,但使用的是普通值。它需要是一个Tk变量(例如:StringVar
)下面是您的代码的一个版本,其中修复了这些问题:
顺便说一下,你是
from Tkinter import *
还是import Tkinter as tk
是一个风格问题。我喜欢后者,因为毫无疑问哪个模块包含类或常量的名称。如果导入的名称与文件中的其他代码冲突,则执行import *
可能会导致问题。我把foo和nac作为主体类的成员变量
然后在naccheck()中引用self.nac
不要忘记更改ck1的变量=self.nac 而ent的textvariable=self.foo。
另外,您可能希望将ck1和ent成员变量设为变量,因为稍后使用naccheck()引用它们时可能会遇到问题
这些改变对我的Python很有效
相关问题 更多 >
编程相关推荐