如何获取选中的单选按钮的值?

How to get the value of the selected radio button?

我想创建两组不同的单选按钮。用户将从任一组中选择 select 个选项。将有一个函数可以从 selected 单选按钮获取值(字符串),然后打印它们。这是我的代码,但它不起作用(我是 python 的新手)。

from tkinter import *
root = Tk()
btn1 = "lol"
btn2 = "lel"
def funkcija():
    n = entry1.get()
    m = "null"
    X = btn1.get()
    Y = btn2.get()
    print("%s %s je %s %s." % (n, X, m, Y))


theLabel = Label(root, text="Vnesite količino in izberite prvo valuto.")
theLabel.grid(row=0, columnspan=3)

gumb1=Radiobutton(root,text="Euro",value = "euro",variable = "btn1").grid(row=2, column=1, sticky=W)
gumb2=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn1").grid(row=3, column=1, sticky=W)
gumb3=Radiobutton(root,text="Funt",value = "funt",variable = "btn1").grid(row=4, column=1, sticky=W)

label3= Label(root, text="Izberite drugo valuto.")
label3.grid(row=6, columnspan=3)

label35= Label(root)
label35.grid(row=5, columnspan=3)

gumb4=Radiobutton(root,text="Euro",value = "euro",variable = "btn2").grid(row=7, column=1, sticky=W)
gumb5=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn2").grid(row=8, column=1, sticky=W)
gumb6=Radiobutton(root,text="Funt",value = "funt",variable = "btn2").grid(row=9, column=1, sticky=W)

label1 = Label(root, text="Količina:")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)

go = Button(root, text="Izračun", fg="white", bg="black", command=funkcija)
go.grid(row=10, columnspan=3)

root.mainloop()

在您的单选按钮中,分析您传递的参数:

gumb1 = Radiobutton(root,
                    text = "Euro",
                    value = "Euro",
                    variable = "btn2"

参数valuevariable是存储单选按钮数据的。您已正确设置 value 选项。选择单选按钮时,解释器将自动设置 variablevalue

但这就是您的问题所在:

variable = "btn2"

"btn2" 是一个字符串。虽然不是很有用,是吗?事实上,您正在尝试对其执行甚至不存在的方法。比如这里:

def funkcija():
    X = btn2.get()

事实上,有了这些信息,您就快到了!

在脚本的顶部,您需要将 btn2 设置为 Tkinter 的 StringVar,如下所示:

from tkinter import *
btn1 = StringVar()
btn2 = StringVar()

现在已经完成了,让我们更改单选按钮中的参数。

gumb1 = Radiobutton(root,
                text = "Euro",
                value = "Euro",
                variable = btn2

现在,Tkinter 将在选择时自动更新变量。要获得该值,请执行与 funkcija.

中相同的操作
X = btn2.get()

然后btn2的值(由单选按钮更新)将不会被读取,并存储到变量X