A-Ronasaurus
A-Ronasaurus

Reputation: 15

Tkinter Checkbox with if statement issues

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?

Upvotes: 0

Views: 1486

Answers (1)

bashBedlam
bashBedlam

Reputation: 1500

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

Upvotes: 1

Related Questions