Radiobutton在Tkinter调用函数

时间:2015-07-06 17:19:49

标签: python button tkinter radio-button invoke

我在tkinter中有单选按钮的代码。我正在努力编写调用button命令的代码。基本上我希望用户能够选择时间范围和人。我有三个不同的文件运行三种不同的数据分析,所以我希望运行三个文件,但只从时间范围和该人那里获取数据。

from Tkinter import *

class RBDemo:
    def __init__(self, win):
        self.v = IntVar()

        #Put the first group of radio buttons in their own frame.
        f1 = Frame(win, borderwidth=3, relief=RAISED)
        rb1 = Radiobutton(f1, text="This Week", variable=self.v, value=1)
        rb2 = Radiobutton(f1, text="This Month", variable=self.v, value=2)
        rb3 = Radiobutton(f1, text="This Year", variable=self.v, value=3)
        rb1.pack(anchor=W);  rb2.pack(anchor=W);   rb3.pack(anchor=W)
        f1.pack(side=LEFT)

        #Button one will be selected by default
        self.v.set(1)


        #Make a second group of radiobuttons in their own frame.
        #Make first button the default
        self.v2 = StringVar()
        f2 = Frame(win, borderwidth=2, relief=SOLID)

        rb4 = Radiobutton(f2, text="Bob", variable=self.v2, value="Bob")
        rb5 = Radiobutton(f2, text="Stacy", variable=self.v2, value="Stacy")
        rb6 = Radiobutton(f2, text="Both", variable=self.v2, value="Both") 
        rb4.pack(anchor=W);  rb5.pack(anchor=W); rb6.pack(anchor=W)
        f2.pack(side=RIGHT)
        self.v2.set("Bob")

        #Make a button that prints what each value is when clicked
        b = Button(win, text="Let's do this!", command=self.clicked)
        b.pack(side=BOTTOM, fill=BOTH, expand=1)


    def clicked(self):
        print("button clicked!")
        print("v is:", self.v.get())
        print("v2 is:", self.v2.get() )




mw = Tk()
app = RBDemo(mw)
mw.mainloop()

我试过

    def selected(self):
    if self.my_var.get()==1:
        "do something"
        elif self.my_var.get()==2:
            "do something"
            else:
                "do something"

但这似乎不起作用,考虑到我必须使用按钮的输入运行三个文件,它也不是非常pythonic。

1 个答案:

答案 0 :(得分:1)

首先,正确缩进时,if - elif块完全可以。所以你可以使用

if whatevervar.get() == 1:
    dosomethingfancy()
elif whatevervar.get() == 2:
    dosomethingcool()
#and so on

在其他语言中有类似switch的情况:wikipedia在Python中没有这样的构造,但有一个简洁的小技巧,特别是在处理更大的代码块时有用:

Options = {
         1: dosomething,
         2: dosomethingelse
}

#execution
Options[myvar.get()]()

基本上,定义了一个字典,将其键值映射到函数。注意括号:当定义字典时,你不想调用函数。