Python Checkbutton reads value only once
Clash Royale CLAN TAG#URR8PPP
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
You need to check the value of number
; you can do this by assigning a command to print number
, when the button is clicked:
number
number
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
No, mainloop keeps the gui responsive and listening to interactions; it does not run arbitrary code on its own.
– Reblochon Masque
Aug 6 at 10:02
Oh okay, thanks a lot. All questions've been answered.
– Quotenbanane
Aug 6 at 10:06
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
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?
– Quotenbanane
Aug 6 at 10:00