I have a tkinter GUI that I'm working on in Python 3.8 on my Macbook. I've encountered a problem where changing the variable associated with a checkbutton doesn't change the appearance of the checkbutton itself. I'd like the checkbutton to show up as checked if I set the IntVar() associated with it to 1, and from everything I've read, this should be happening.
Here's some extremely simplified code showing the problem:
import tkinter as tk
class Window():
def __init__(self, master):
var = tk.IntVar()
checkbutton = tk.Checkbutton(master, variable=var)
checkbutton.pack()
var.set(1)
root = tk.Tk()
Window(root)
root.mainloop()
When I run the script, the checkbutton isn't checked. I am still able to check the checkbutton by clicking on it though. Is this a known bug or am I missing something?
Solved: The issue, as jasonharper pointed out, was garbage collection. The tkinter variable wasn't being used for anything and was just being stored as a local variable, so it was thrown out and couldn't be referenced by the checkbutton. Saving the IntVar somewhere that stuck around fixed the problem. One solution was saving the variable in the var attribute of the checkbutton itself:
import tkinter as tk
class Window():
def __init__(self, master):
var = tk.IntVar()
checkbutton = tk.Checkbutton(master, variable=var)
checkbutton.pack()
var.set(1)
checkbutton.var = var
root = tk.Tk()
Window(root)
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With