TKInter Python检查按钮状态

时间:2017-12-19 10:05:01

标签: python tkinter

如果检查了某些检查按钮,我正在尝试对文本文件进行一些操作。

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

致电

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

为每个变量输出0或1,但是当我尝试使用该值做某事时,它似乎不会调用代码。

if var2.get(): <--- does this mean if = 1?
    Do something

1 个答案:

答案 0 :(得分:1)

在下面的示例[a]中,如果var.get()False,则会在命令提示符中打印,如果是lbl['text']则更新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()

但是代码永远不会print"0""1" 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()