使用checkbutton禁用小部件?

时间:2011-05-25 19:40:08

标签: python checkbox tkinter

如何使用checkbutton禁用一个条目...我得到了这个但它不起作用(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 个答案:

答案 0 :(得分:3)

您的代码有很多小问题。例如,Principle继承自tk.Tk,但您不会以名称tk导入Tkinter。

其次,您不需要全局变量。您应该使用实例变量。

第三,由于“nac”是IntVar,您需要使用get方法来获取值。

最后,您使用foo作为textvariable属性的值,但您使用的是普通值。它需要是一个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 *会导致问题。

答案 1 :(得分:2)

我创建了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上运行良好

相关问题