1

I have a set of Checkbuttons on root.frame1 and I want to use the selected ones in a subframe of root to make an optionmenu. The approach I have taken is:

import Tkinter as Tk
root = Tk.Tk()
frame1 = Tk.Frame(root)
variables = dict()
s = {'WZ':'1','ZB':'2','RS':'3','CC':'4','CL':'5'}
for k,v in s.iteritems():
     variables[k]= Tk.IntVar()
     cb = Tk.Checkbutton(frame1, text=v,onvalue=v, offvalue=0, variable=variables[k], anchor=W)
     cb.pack(side='top',fill='x')

frame1.pack()

and then when I select some of the checkbuttons, the values in the variables dictionary are still 0:

for k,v in variables.iteritems():
      print k,' ',v.get()

which prints out:

'WZ' 0
'ZB' 0
....

I tried to use a list of tuples instead of a dictionary i.e. variables =[('WZ',),...] but still the values don't change. Do you know what is wrong with my code? Please let me know. Thanks Ali

3
  • I'd change some parts, but your code works for me. Have you tried replacing Tk.IntVar() with Tk.IntVar(frame1)? Commented May 30, 2013 at 21:48
  • The code also works for me on a Mac with python 2.7. Can you show a complete working program, so we can see how you're printing the values out? My guess is, you're somehow printing them before the mainloop runs. Commented May 31, 2013 at 1:18
  • That's right. Being a newbie to Tkinter, I was printing the variables before running the mainloop. Commented May 31, 2013 at 10:24

1 Answer 1

2

Your code works for me. However, it would help to work with runnable code. Does this work for you?

import Tkinter as tk

class App(object):
    def __init__(self, master, **kwargs):
        frame = tk.Frame(master)
        self.variables = {}
        s = {'WZ':1,'ZB':2,'RS':3,'CC':4,'CL':5}
        for k, v in s.iteritems():
             self.variables[k] = tk.IntVar()
             cb = tk.Checkbutton(
                 frame, text=k, onvalue=v, offvalue=0,
                 variable=self.variables[k],
                 command=self.oncheck(k),
                 anchor='w')
             cb.pack(side='top',fill='x')
        frame.pack()
    def oncheck(self, key):
        def _oncheck():
            print('{l} => {v}'.format(l=key, v=self.variables[key].get()))
        return _oncheck

root = tk.Tk()
app = App(root)
root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that works great. I should've run the mainloop(). The only difference is in my s dictionary the values are strings and when I define the onvalue to be a string, the checkbuttons appear disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.