繁体   English   中英

获取所选检查按钮的文本 - tkinter

[英]Get the text of selected checkbutton- tkinter

我正在 tkinter 中构建一个 gui,我有 3 个 Checkbuttons:

    var1 = IntVar () #assing variable for the model selection- user select PLS
    Checkbutton (top, text="PLSR", variable=var1).grid (row=11,column=1,sticky='W' )
    var2 = IntVar () #user select RF model
    Checkbutton (top, text="Random forest", variable=var2).grid (row=12, column=1,sticky='W' )
    var3=IntVar () #user select SVR model
    Checkbutton (top, text="SVR", variable=var3).grid (row=13, column=1,sticky='W')

我想获取所选复选按钮的文本(PLSR/RF/SVR)。 如果用户 select 第一个,我想打印 PLSR 等等。 我知道方法 cget("text") 但我怎么知道从三个中选择了哪个检查按钮?(只能选择一个)

您可以使用以下命令,然后只需读取“whichButton”的值即可确定选择了哪个按钮。

whichButton = ""
    
def command1():
       global whichButton
       whichButton = "PLSR"
       print(whichButton)

    
def command2():
       global whichButton
       whichButton = "Random forest"
       print(whichButton)

def command3():
       global whichButton
       whichButton = "SVR"
       print(whichButton)

Checkbutton (top, text="PLSR", variable=var1,command=command1).grid (row=11,column=1,sticky='W' )

Checkbutton (top, text="Random forest", variable=var2,command=command2).grid (row=12, 
        column=1,sticky='W' )

Checkbutton (top, text="SVR", variable=var3,command=command3).grid (row=13, column=1,sticky='W')

您可以尝试单选按钮 function。 像这样python var1 = StringVar() #variable var1 = Radiobutton(text="Paid", font=("Arial Rounded MT Bold", 15),variable=var1,value="Paid").place(x=520, y=290)

复选按钮用于执行多项选择。 如果你想让用户只做一个选择,你应该使用 Radiobutton。 不仅因为这就是 tkinter 的设计方式,还因为单选按钮和复选按钮之间的区别是普遍的,并且大多数用户都很好理解。

当您使用两个或更多单选按钮时,它们应该共享相同的值。 要确定选择了哪个按钮,您只需要获取那个变量即可。 如果要获取字符串而不是 integer,请使用StringVar

var = StringVar(value="PLSR")
Radiobutton (top, text="PLSR", variable=var, value="PLSR")
Radiobutton (top, text="Random forest", variable=var, value="Random forest")
Radiobutton (top, text="SVR", variable=var, value="SVR")

使用上面的代码,当您获得变量的值时,您将获得“PLSR”、“随机森林”或“SVR”。

截屏

暂无
暂无

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

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