0

Having some difficulty using an if statement with the checkbuttons. I tried this any many other variations: How to get state of Checkbutton when it's selected?

uvcheckvar = tk.IntVar()
uvcheckvar.set(0)

c1 = tk.Checkbutton(leftframeobjcol, text="UV", variable = uvcheckvar,
    command=reset) #I've tried setting their onvalue = 1 and offvalue = 0 as well
c1.pack()

if checkvar.get() == 1: #or I've tried 'if checkvar.get() and checkvar == 1
    print("test")

Doesn't seem to work for some reason. My goal is to have it print something once I click the checkbox (a test at this point. Long term looking to change an array). I can't seem to find the solution as the link provided above does not solve my problem. Surely this is an easy fix somehow? Am I misunderstanding something?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

What you need to do is associate a command function that gets the variable when the checkbox is checked. Like this :

import tkinter as tk

root = tk.Tk ()

is_checked = tk.IntVar ()
def check_checkbox () :
    if is_checked.get () == 1:
        print ("test success")

c1 = tk.Checkbutton(root, text="UV", onvalue = 1, offvalue = 0,
        variable = is_checked, command = check_checkbox)
c1.pack()

root.mainloop ()
bashBedlam
  • 1,402
  • 1
  • 7
  • 11