Python 2.7 Tkinter - 确定已选择哪个单选按钮 [英] Python 2.7 Tkinter - Determine which Radiobutton has been selected

查看:29
本文介绍了Python 2.7 Tkinter - 确定已选择哪个单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设已经编写了以下代码:

Assuming the following code has been written:

self.firstRadioButton = Radiobutton(self.__canvas, text="ONE", fg='white', bg=BACKGROUND_COLOR, variable=self.selectedONE, value=1)

self.secondRadioButton = Radiobutton(self.__canvas, text="TWO", fg='white', bg=BACKGROUND_COLOR, variable=self.selectedTWO, value=2)

我试图确定哪个单选按钮被选中,然后提取用户选择的任何一个的值.我该怎么做?

I am trying to determine which radio button has been selected and then extract the value of whichever one the user picks. How do I do this?

推荐答案

关键是要确保两个单选按钮共享相同的变量.然后,要知道选择了哪一个,您只需要获取变量的值.

The key is to make sure that both radiobuttons share the same variable. Then, to know which one is selected you simply need to get the value of the variable.

这是一个例子:

import tkinter

# function that is called when you select a certain radio button
def selected():
    print(var.get())


root = tkinter.Tk()

var = tkinter.StringVar() #used to get the 'value' property of a tkinter.Radiobutton

# Note that I added a command to each radio button and a different 'value'
# When you press a radio button, its corresponding 'command' is called.
# In this case, I am linking both radio buttons to the same command: 'selected'

rb1 = tkinter.Radiobutton(text='Radio Button 1', variable=var, 
                          value="Radio 1", command=selected)
rb1.pack()
rb2 = tkinter.Radiobutton(text='Radio Button 2', variable=var, 
                          value="Radio 2", command=selected)
rb2.pack()

root.mainloop()

这篇关于Python 2.7 Tkinter - 确定已选择哪个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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