[英]tkinter radiobutton not updating variable
--更新:我改变了
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.
啊! 我相信我已经知道了。 我有完全相同的问题。 确保您将一个主self.rbv=tk.IntVar(master) #or 'root' or whatever you are using)
分配给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()
尝试运行该命令,单击不同的按钮(它们是单选按钮,但带有indicatoron = False),您将看到它打印正确更改的值!
你很亲密 只需从self.optionVal.get()
取出.get()
self.optionVal.get()
。 Radiobutton
构造函数期望一个跟踪的变量,而是给它赋值该变量的结果。
你需要:
variable=self.optionVal
函数中的variable=self.optionVal
参数中删除.get()
按钮。 您要传递变量,而不是变量的评估值; 和 command=self.selected()
删除括号,然后改用command=self.selected
。 括号中的内容为“立即调用此函数并将返回值用作回调”。 相反,您想将函数本身用作回调。 为了更好地理解这一点,您需要研究闭包:一个函数可以返回一个函数(如果是这种情况,它将用作您的回调)。 编辑:快速提醒,还:Python未编译,但已解释。 在解释脚本时,将调用您的回调。
def view(interface):
choice = interface.v.get()
if choice == 0:
output = "0"
elif choice == 1:
output = "1"
elif choice == 2:
output = "2"
elif choice == 3:
output = "3"
else:
output = "Invalid selection"
return tk.messagebox.showinfo('PythonGuides', f'You Selected {output}.')
class Start:
def __init__(self):
self.root = tk.Tk()
self.root.geometry('500x500')
self.root.resizable(False, False)
self.root.title('find out the degree of severity')
self.v = tk.IntVar()
dolori_ossa = {"nessun dolore": 0,
"dolori articolari": 1,
"frattura composta": 2,
"frattura scomposta": 3}
for (txt, val) in dolori_ossa.items():
tk.Radiobutton(self.root,
text=txt,
variable=self.v,
value=val,
command=lambda:view(self)
).pack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.