Disable widget using checkbutton button?

How can I disable recording using checkbutton ... I got this, but it doesn't work (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()
+3
source share
2 answers

I created a member variable foo and nac of class Principal

    ...
    self.foo = StringVar()
    self.foo.set("test")
    self.nac = IntVar()
    ...

Then in naccheck () the link is self.nac

    def naccheck(self):
        if self.nac == 1:
            ent.configure(state='disabled')
            self.nac = 0
        else:
            ent.configure(state='normal')
            self.nac = 1

Remember to change the variable ck1 = self.nac and ent textvariable = self.foo.

Alternatively, you can create the variable ck1 and ent member, as you may have problems with their link later using naccheck ()

These changes worked fine on my Python2.7

+1
source

There are many small things in the code. First, Principleinherits from tk.Tk, but you do not import Tkinter under the name tk.

-, . .

-, "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 * , - , .

+3

All Articles