繁体   English   中英

如何在不分配 IntVar 的情况下确定是否选中了复选按钮?

[英]How can I determine whether a checkbutton is checked without assigning an IntVar?

我想在不分配 IntVar 的情况下检查复选按钮的 state。

除非必要,否则我不想将冗余变量关联到程序中的每个复选框。 似乎这应该是可能的,因为 tkinter 记录了一个复选按钮的 state,无论我是否分配了一个 IntVar。

下面的代码创建了一个包含 3 个可检查选项的菜单,每个选项都分配了一个 IntVar。 IntVars 根据是否选中选项按预期更新。 我尝试确定是否使用 entrycget 检查了选项,这给出了代码中指出的错误。

有没有更Pythonic的方式来做到这一点?

from tkinter import *
root = Tk()
root.geometry("200x400")

#This routine should print '1' if option 0 is checked and "0" when not checked
def menucallback():
               
    print(f"Checked = {menuCheckbuttonStates[0].get()}") #works correctly

    #this prints "active" if the mouse was over option 0 regardless of checked state
    print(mb.menu.entrycget(0, "state"))

    #printing checked option 0 using the value of entrycget should show the underlying IntVar,
    #but it throws an error '_tkinter.TclError: unknown option "-value" '
    #var=(mb.menu.entrycget(0, "value"))

    #printing checked option 0 using the variable of entrycget does not work as I expected            
    var=(mb.menu.entrycget(0, "variable"))
    print(var) # prints "PY_VAR0"          
    #print(var.get()) #throws error "AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'get'"

#setup a menubutton with a menu
mb=Menubutton(root, text="Expand Menu", relief=RAISED)
mb.menu=Menu(mb, tearoff=0)
mb["menu"]=mb.menu

#initialize a variable array to hold checkbutton states
menuCheckbuttonStates=[] 

#add checkable options to the menu
options=['option 0','option 1','option 2']            
for x in options:
    y=IntVar()
    menuCheckbuttonStates.append(y)
    mb.menu.add_checkbutton(label=x, variable=y, onvalue=1, offvalue=0, command=menucallback)

mb.pack()
root.mainloop()

除非必要,否则我不想将冗余变量关联到程序中的每个复选框。

变量不是多余的。 无论您是否显式分配,复选按钮都会有与其关联的变量。

不过,您不必给它一个明确的变量名。 你可以要求tkinter给你变量名,然后用getvar方法得到那个变量的值。

这是您的回调的简化版本,它打印出所有复选按钮的值。 它利用了这样一个事实,即您可以通过菜单项文本查找菜单项的值。

def menucallback():
    for label in ["option 0", "option 1", "option 2"]:
        varname=self.mb.menu.entrycget(label, "variable")
        print(f"{label} = {self.getvar(varname)}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM