用checkbutton禁用小部件?

2024-09-27 00:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用复选按钮禁用条目。。。我有这个,但它不起作用(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()

Tags: selfprincipalfooconfiguredefroot按钮global
2条回答

你的代码有很多小问题。首先,Principletk.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 *可能会导致问题。

我把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()引用它们时可能会遇到问题

这些改变对我的Python很有效

相关问题 更多 >

    热门问题