Python Tkinter - 在 Radiobutton 上获取选择 [英] Python Tkinter - get selection on Radiobutton

查看:23
本文介绍了Python Tkinter - 在 Radiobutton 上获取选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检索单击的 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 ?

设置单选按钮的代码是:

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)

推荐答案

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

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)

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

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

which_button_is_selected = radio_var.get()

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

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

这篇关于Python Tkinter - 在 Radiobutton 上获取选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆