1

Python Checkbutton reads value only once

I've looked in StackOverflow for any similar problems, but the only one that looked similar was this here. It suggested that in this case the variable should be set global but I don't think that's a good solution. So I'm asking you guys for a better one.

I want to use Checkbutton() in Python and my code looks (simplified) like this...

#!/usr/bin/env

from Tkinter import *

Fenster = Tk()
Fenster.title ("Sensors")

Number = IntVar()
Button = Checkbutton(Fenster, text = "Check me", variable = Number, onvalue = 1, offvalue = 0)

print Number.get()

Button.pack()

mainloop()

When i run this code, the window opens and i see the Checkbox. So far so good. But when I want to check or uncheck it, the value of "Number" somehow doesn't change. It only displays "1", probably from the first frame, and never changes.

Could you give me some advice how to improve this?

1 Answer 1

1

You need to check the value of number; you can do this by assigning a command to print number, when the button is clicked:

import tkinter as tk   # <-- avoid star imports

def f():
    print(number.get())

fenster = tk.Tk()
fenster.title ("Sensors")

number = tk.IntVar()
button = tk.Checkbutton(fenster, text="Check me", variable=number, command=f)

button.pack()

fenster.mainloop()   # call mainloop on your root window
Sign up to request clarification or add additional context in comments.

3 Comments

Worked perfectly, thanks. But why isn't the original code working? With mainloop() shouldn't the code print the value again and again each frame?
No, mainloop keeps the gui responsive and listening to interactions; it does not run arbitrary code on its own.
Oh okay, thanks a lot. All questions've been answered.

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.