-1

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 :(

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
savyexe
  • 3
  • 4

1 Answers1

0

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')
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Okay, that makes a lot of sense but on my actual program they have different variables and they still do the same thing :C – savyexe May 26 '20 at 22:51
  • @savyexe: I can only respond to code that you’ve posted. If the checkboxes are “entangled”, the only explanation is that they have the same variable. If your variables are local, this can be a side effect of that. – Bryan Oakley May 27 '20 at 00:30
  • welp, that worked just fine except because the actual value of the variable didn't change, so i added a command function to the checkbutton to change the value of the variable whenever the it's pressed and now it works, thanks for the advice :D – savyexe May 27 '20 at 19:10
  • @savyexe: you shouldn't need to do that. The checkbutton will automatically set the value of the associated variable. If it's not doing that, you're doing something wrong. – Bryan Oakley May 27 '20 at 19:18