【问题标题】:Python Tkinter - get selection on RadiobuttonPython Tkinter - 在 Radiobutton 上获得选择
【发布时间】:2016-07-18 23:01:12
【问题描述】:

我需要检索 Radiobutton clicked 的值,然后使用这个值。

获取单选按钮点击的值的方法是什么?

设置单选按钮的代码是:

radio_uno = Radiobutton(Main,text='Config1', value=1,variable = 1)
radio_uno.pack(anchor=W,side=TOP,padx=3,pady=3)
radio_due = Radiobutton(Main,text='Config2', value=2,variable =1)
radio_due.pack(anchor=W,side=TOP,padx=3,pady=3)
radio_tre = Radiobutton(Main,text='Config3', value=3,variable = 1)
radio_tre.pack(anchor=W,side=TOP,padx=3,pady=3)

【问题讨论】:

    标签: python tkinter radio-button


    【解决方案1】:

    这是一种解决方案: 创建一个tk.IntVar() 来跟踪按下了哪个按钮。我假设你做了一个from tkinter import *。

    radio_var = IntVar()
    

    您需要更改声明按钮的方式:

    radio_uno = Radiobutton(Main,text='Config1', value=1,variable = radio_var)
    radio_due = Radiobutton(Main,text='Config2', value=2,variable = radio_var)
    radio_tre = Radiobutton(Main,text='Config3', value=3,variable = radio_var)
    

    然后使用get()方法查看radio_var的值:

    which_button_is_selected = radio_var.get()
    

    然后您可以创建一个 enum 或仅三个 if 子句,根据选择的按钮执行操作:

    if(which_button_is_selected == 1):
        #button1 code
    elif(which_button_is_selected == 2):
        #button2 code
    else(which_button_is_selected == 3):
        #button3 code
    

    【讨论】:

    • 这不仅仅是一个解决方案,而是正确解决方案。
    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    相关资源
    最近更新 更多