Python Tkinter - get selection on Radiobutton

霸气de小男生 提交于 2020-05-18 08:03:17

问题


I need to retrieve the value of Radiobutton clicked and then use this value .

What is the way to retrieve the value of a Radiobutton clicked ?

the code to setup the Radiobutton is:

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)

回答1:


This is one solution: Create a tk.IntVar() to track which button was pressed. I'm assuming you did a from tkinter import *.

radio_var = IntVar()

You'll need to change the way you declared your buttons:

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)

Then use the get() method to view the value of radio_var:

which_button_is_selected = radio_var.get()

Then you can make an enum or just three if clauses that'll do stuff depending on which button is chosen:

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


来源:https://stackoverflow.com/questions/36317346/python-tkinter-get-selection-on-radiobutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!