【发布时间】:2015-09-23 22:56:41
【问题描述】:
我在 tkinter 中有单选按钮的代码。我正在努力编写调用按钮命令的代码。基本上我希望用户能够选择一个时间范围和一个人。我有三个不同的文件,它们运行三种不同的数据分析,所以我希望这三个文件运行,但只从时间框架和那个人那里获取数据。
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。
【问题讨论】:
-
一个简短的
if..elif..else块完全符合 Python 风格(正确缩进时)。 -
你的代码缩进不正确。
-
您还应该将 self.my_var 替换为 self.v ...
标签: python button tkinter radio-button invoke