- 更新: 我改变了
variable=self.optionVal.get()
到
variable=self.optionVal
但没有改变。我也想知道为什么在编译时会自动调用self.selected?
----原件:
我正在努力熟悉radiobutton,但我不认为我理解radiobutton是如何工作的。这是一个简短的演示代码:
self.optionVal = StringVar()
for text, val in OPTIONS:
print(text,val)
radioButton = Radiobutton(self,
text=text,
value=val,
variable=self.optionVal.get(),
command = self.selected())
radioButton.pack(anchor=W)
def selected(self):
print("this option is :"+self.optionVal.get())
In my opinion this should work like once I choose certain button, and it prints out "this option is *the value*", however now what it does is once compiled, it prints out everything, and the self.optionVal.get() is blankspace, as if value wasn't set to that variable.
I wonder what happens to my code,
Many thanks in advance.
答案 0 :(得分:6)
AHA!我相信我已经弄清楚了。我有完全相同的问题。确保将主人分配给IntVar,如self.rbv=tk.IntVar(master) #or 'root' or whatever you are using)
:
import Tkinter as tk
import ttk
class My_GUI:
def __init__(self,master):
self.master=master
master.title("TestRadio")
self.rbv=tk.IntVar(master)#<--- HERE! notice I specify 'master'
self.rb1=tk.Radiobutton(master,text="Radio1",variable=self.rbv,value=0,indicatoron=False,command=self.onRadioChange)
self.rb1.pack(side='left')
self.rb2=tk.Radiobutton(master,text="Radio2",variable=self.rbv,value=1,indicatoron=False,command=self.onRadioChange)
self.rb2.pack(side='left')
self.rb3=tk.Radiobutton(master,text="Radio3",variable=self.rbv,value=2,indicatoron=False,command=self.onRadioChange)
self.rb3.pack(side='left')
def onRadioChange(self,event=None):
print self.rbv.get()
root=tk.Tk()
gui=My_GUI(root)
root.mainloop()
尝试运行它,单击不同的按钮(它们是radiobuttons但是指示符= False),您将看到它正确打印更改的值!
答案 1 :(得分:2)
你非常接近。只需从.get()
中取出self.optionVal.get()
即可。 Radiobutton
构造函数需要一个跟踪变量,而是给它评估该变量的结果。
答案 2 :(得分:1)
你需要:
.get()
参数中删除variable=self.optionVal
。您想传递变量,而不是变量的评估值;和command=self.selected()
移除括号,然后使用command=self.selected
。括号表示&#34;现在调用此函数并使用返回值作为回调&#34;。相反,您希望将函数本身用作回调。为了更好地理解这一点,你需要学习闭包:一个函数可以返回一个函数(如果是这样的话,那将用作你的回调)。编辑:快速提醒一下:Python不是编译的,而是解释的。当脚本被解释时,正在调用您的回调。