Search code examples
pythonselecttkinterdeselect

Selecting one checkbox deselects other options in tkinter


I have an LED panel with UV, Green, and Blue. Trying to figure out how once I click "No Light" (option 4) how it would disable or deselect the first three checkbuttons (uv, green, blue)? I saw different options here:

https://www.tutorialspoint.com/python/tk_checkbutton.htm

but I don't know how to connect them. Any thoughts would really help since I'm pretty new to Python/coding. Appreciate any insights. Thank you!

checkvar1 = tk.IntVar()
checkvar2 = tk.IntVar()
checkvar3 = tk.IntVar()
checkvar4 = tk.IntVar()

c1 = tk.Checkbutton(leftframeobjcol, text="UV", variable = checkvar1)
c1.pack(anchor="w")
c2 = tk.Checkbutton(leftframeobjcol, text="Green", variable = checkvar2)
c2.pack(anchor="w")
c3 = tk.Checkbutton(leftframeobjcol, text="Blue", variable = checkvar3)
c3.pack(anchor="w")
c4 = tk.Checkbutton(leftframeobjcol, text="No light", variable = checkvar4)
c4.pack(anchor="w")

Solution

  • You can assign a callback using command option for the four Checkbutton and in the callback, reset the other three checkbuttons or reset the No light checkbutton based on the passed value of the callback and the current states of the checkbuttons:

    def reset(flag=False):
      if flag:
        # 'No light' clicked
        if checkvar4.get():
          checkvar1.set(0)
          checkvar2.set(0)
          checkvar3.set(0)
      else:
        # other light clicked, reset 'No light' if any one of the others is checked
        checkvar4.set(0 if checkvar1.get() or checkvar2.get() or checkvar3.get() else 1)
    
    
    c1 = tk.Checkbutton(leftframeobjcol, text="UV", variable=checkvar1, command=reset)
    c1.pack(anchor="w")
    c2 = tk.Checkbutton(leftframeobjcol, text="Green", variable=checkvar2, command=reset)
    c2.pack(anchor="w")
    c3 = tk.Checkbutton(leftframeobjcol, text="Blue", variable=checkvar3, command=reset)
    c3.pack(anchor="w")
    c4 = tk.Checkbutton(leftframeobjcol, text="No light", variable = checkvar4, command=lambda:reset(True))
    c4.pack(anchor="w")