Search code examples
pythonpython-3.xwindowstkintertkinter.checkbutton

Entanglement between Tkinter Checkbuttons


Hey so i'm making a program that has a checkbutton on the main window and a toplevel window that has one aswell. the problem is that for some reason the toplevel checkbutton affects the state of the main checkbutton, or the main checkbutton mimics the top level one (if you check/uncheck the toplevel one, the main one checks/unchecks aswell). Here's an example code which displays the problem:

import tkinter as tk

def toplevel():
    top = tk.Toplevel()
    top.geometry('200x50')

    top_chekbutton = tk.Checkbutton(top, text='top')

    top_chekbutton.pack()

    top.mainloop()

main = tk.Tk()
main.geometry('200x50')

open_top = tk.Button(main, text='open top', command=toplevel)

main_checkbutton = tk.Checkbutton(main, text='main')

main_checkbutton.pack()
open_top.pack()

main.mainloop()

i didn't define the state variables because they don't seem to be the source of the problem. i'm using python 3.7.7 and tkinter 8.6 on win10. plz help :(


Solution

  • As a general rule of thumb, every instance of Checkbutton should have a variable associated with it. If you don't, a default value will be used that is identical for all Checkbuttons. All widgets that share the same variable will display the same value.

    You can verify this yourself by printing out the value of top_chekbutton.cget("variable") and main_checkbutton.cget("variable"). In both cases the value is "!checkbutton" (at least, with the version of python I'm using).

    So, assign a variable for your checkbuttons, such as a BooleanVar, IntVar, or StringVar.

    main_var = tk.BooleanVar(value=False)
    main_checkbutton = tk.Checkbutton(main, text='main')