如何使用单选按钮将变量的整数输入?

时间:2011-10-15 23:48:06

标签: python string input radio-button tkinter

我使用下面的代码行在多选命令行软件中为“BAI_var1”输入变量。

BAI_var1 = input ("Please enter 0 for not at all, 1 for somewhat, 2 for moderatly or 3 for a lot:")

这是我的图形用户界面:

from Tkinter import *
import time

    class App:
        def __init__(self, master):
            w = Label(master, text="1. Anxiety, nervousness, worry or fear")
            w.pack()

            v = IntVar()
            Radiobutton(master, text="0 for not at all", variable=v, value=1).pack(side=TOP, anchor="w")
            Radiobutton(master, text="1 for somewhat", variable=v, value=2).pack(side=TOP, anchor="w")
            Radiobutton(master, text="2 for moderatly", variable=v, value=3).pack(side=TOP, anchor="w")
            Radiobutton(master, text="3 for a lot", variable=v, value=4).pack(side=TOP, anchor="w")

            self.button = Button(master, text="BACK", fg="red", command=self.button6)
            self.button.pack(side=BOTTOM)
            self.button = Button(master, text="NEXT", fg="red", command=self.button5)
            self.button.pack(side=BOTTOM)


        def button6(self):
            print "Sam is awesome!GAJONGA" 

        def button5(self):
            print "PYTHON FOR THE WIN! GIAN SAYS PYTHON = FILTHY" 

    master = Tk()
    app = App(master)
    master.mainloop()

我的问题是我不知道如何使用 Radiobutton 向变量输入设定的整数。

1 个答案:

答案 0 :(得分:0)

使用字典将整数值映射到它们代表的字符串:

choices = {
    1: "not at all",
    2: "somewhat",
    3: "moderately",
    4: "a lot"
}

然后,您可以使用它来创建UI:

for (i in sorted(choices.keys())):
    label = "%s - %s" % (i, choices[i])
    rb=Radiobutton(master, text=label, variable=v, value=i)
    rb.pack(side=TOP, anchor="w")

当你需要获取值时,显然它只是一个简单的字典查找,使用变量的值作为键。