1

I am trying to do some work on a text file if certain checkbuttons are checked.

"Populate CheckBoxes"
Label(master, text="Pick at least one index:").grid(row=4, column=1)
Checkbutton(master, text="Short",variable=var1).place(x=5,y=60)
Checkbutton(master, text="Standard",variable=var2).place(x=60,y=60)
Checkbutton(master, text="Long",variable=var3).place(x=130,y=60)

Calling

print("Short: %d,\nStandard: %d,\nLong: %d" % (var1.get(), var2.get(), 
      var3.get()))

prints out 0 or 1 for each variable but when I am trying to use that value to do something it does'nt seem to call the code.

if var2.get(): <--- does this mean if = 1?
    Do something
2
  • In if something:, something will be considered True if it is not False, 0, [], '', {}, None, ... Most empty objects (list, dictionary, string, tuple, ...) are considered False, but everything else is considered True (not only 1) Commented Dec 19, 2017 at 10:13
  • How are var1, var2, var3 declared exactly? Commented Dec 19, 2017 at 10:18

1 Answer 1

1

In below example var.get()'s value is printed in command prompt if it's False and updates the lbl['text'] if it's True:

import tkinter

root = tkinter.Tk()

lbl = tkinter.Label(root)
lbl.pack()

var = tkinter.BooleanVar()

def update_lbl():
    global var
    if var.get():
        lbl['text'] = str(var.get())
    else:
        print(var.get())

tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()

root.mainloop()

But below code never prints as "0" and "1" are both True:

import tkinter

root = tkinter.Tk()

lbl = tkinter.Label(root)
lbl.pack()

var = tkinter.StringVar()

def update_lbl():
    global var
    if var.get():
        lbl['text'] = str(var.get())
    else:
        print(var.get())

tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()

root.mainloop()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, what is the reason though that when i've clicked the var2 checkbox its not the completing the action of the if statement?
@JonLavercombe are they objects of StringVar?
No they are just exactly as listed above, so if i convert them to string... something like if str(var2.get()):
@JonLavercombe var1, var2, var3 should all be tkinter.BooleanVar or at worst tkinter.IntVar otherwise they may act unpredictably.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.