--更新: 我变了
variable=self.optionVal.get()
到
variable=self.optionVal
但是什么都没有改变。另外我想知道为什么它在编译时自动调用self.selected?
----原文:
我正在尝试熟悉单选按钮,但我认为我不了解单选按钮的工作原理。下面是一个简短的演示代码:
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.
请您参考如下方法:
啊哈!我相信我已经想通了。我有完全相同的问题。确保你正在为 IntVar 分配一个 master,比如 self.rbv=tk.IntVar(master) #or 'root' 或者你正在使用的任何东西):
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()
尝试运行它,单击不同的按钮(它们是单选按钮,但 indicatoron=False),您将看到它打印正确更改的值!
