Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Checkbutton doesn't change my variable

Tags:

python

tkinter

I'm trying to use a Checkbutton with a function, my_var never changes but it always call my function.

here the code:

my_var = False
def controllo_carta():
    global my_var
    print str(my_var)

[...]

c = tk.Checkbutton(toolbar, text="press me",onvalue=True,offvalue=False,variable=my_var,command=controllo_carta)
c.select()
c.pack(side=tk.LEFT,padx=2,pady=2)

print 'my var:' + str(my_var)

[...]

where is my mistake?

thanks!

like image 327
15 revs, 2 users 97% Avatar asked Jan 20 '23 09:01

15 revs, 2 users 97%


1 Answers

To make your code work I would use BooleanVar() and the associated get() method to retrieve its value (http://effbot.org/tkinterbook/variable.htm)

For example: (from: http://effbot.org/tkinterbook/checkbutton.htm)

from Tkinter import *

master = Tk()

var = BooleanVar()

def cb():
    print "variable is {0}".format(var.get())

c = Checkbutton(master, text="Press me", variable=var, command=cb)
c.pack()

mainloop()
like image 116
Victor Avatar answered Jan 29 '23 00:01

Victor