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

时间:2015-04-19 22:18:22

标签: python tkinter radio-button

我想创建2组不同的单选按钮。用户可以从任一组中选择一个选项。将有一个函数可以从所选的单选按钮获取值(字符串),然后打印它们。这是我的代码,但它不起作用(我是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()

1 个答案:

答案 0 :(得分:3)

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

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

参数valuevariable用于存储单选按钮的数据。您已正确设置value选项。选择单选按钮时,解释程序将自动将variable设置为value

但问题出在哪里:

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中。