简体   繁体   English

Python Tkinter - 在 Radiobutton 上获取选择

[英]Python Tkinter - get selection on Radiobutton

I need to retrieve the value of Radiobutton clicked and then use this value .我需要检索单击的 Radiobutton 的值,然后使用此值。

What is the way to retrieve the value of a Radiobutton clicked ?检索单击的 Radiobutton 的值的方法是什么?

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)

This is one solution: Create a tk.IntVar() to track which button was pressed.这是一种解决方案:创建一个tk.IntVar()来跟踪按下了哪个按钮。 I'm assuming you did a from tkinter import * .我假设你做了一个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 :然后使用get()方法查看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:然后,您可以创建一个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

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

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