Disable Widget With Checkbutton?
Solution 1:
I made foo and nac member variable of the Principal class
...
self.foo = StringVar()
self.foo.set("test")
self.nac = IntVar()
...
Then in naccheck() reference self.nac
def naccheck(self):
if self.nac == 1:
ent.configure(state='disabled')
self.nac = 0
else:
ent.configure(state='normal')
self.nac = 1
Dont forget to change ck1's variable = self.nac and ent's textvariable = self.foo.
Also, you might want to make ck1 and ent member variable, as you might have problems referencing them later with naccheck()
Those changes worked fine on my Python2.7
Solution 2:
There are many small things wrong with your code. For one, Principle
inherits from tk.Tk
but you don't import Tkinter under the name tk
.
Second, you don't need global variables. You should use instance variables instead.
Third, since "nac" is a IntVar
you need to use the get
method to get the value.
Finally, you are using foo
as the value of the textvariable
attribute but you are using an ordinary value. It needs to be a Tk variable (eg: StringVar
)
Here's a version of your code with those things fixed:
#!/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()
By the way, whether you do from Tkinter import *
or import Tkinter as tk
is a matter of style. I like the latter because it leaves no doubt which module contains the name of the class or constant. Doing an import *
can cause problems if you import something with a name that clashes with other code in your file.
Post a Comment for "Disable Widget With Checkbutton?"