2016-12-01 20 views
1

--update: 我改变Tkinter的单选按钮不更新变量

variable=self.optionVal.get() 

variable=self.optionVal 

但没有changed.Also我不知道为什么它会自动调用编译时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. 
+1

您需要将**实际变量**作为变量参数传递,而不是调用变量的''.get()''的结果。 – jasonharper

+0

@jasonharper我试过了,但还是没有通过 – angieShroom

回答

2

你很亲密。只需从self.optionVal.get()中取出.get()即可。 Radiobutton构造函数期望一个跟踪变量,您将赋予它评估该变量的结果。

1

您需要:

  1. 在构造函数中的按钮variable=self.optionVal参数中删除.get()。你想传递变量,而不是变量的计算值;和
  2. command=self.selected()中删除括号并使用command=self.selected代替。圆括号表示“现在调用此函数并使用返回值作为回调”。相反,你想使用该函数本身作为回调。为了更好地理解这一点,你需要研究闭包:一个函数可以返回一个函数(并且,如果是这种情况的话,它将被用作你的回调函数)。

编辑:快速提醒,也:Python不编译,但解释。您的回调被称为,解释为

+0

非常感谢你为我澄清这些!我跟着1和2,而现在它只打印出“这个选项是:”当我点击它时,它仍然没有给出相应的self.optionVal.get(),但一直给予空白空间。你有其他想法吗?我认为它不会更新self.optionVal – angieShroom

+0

代码中的'val'和'text'是什么?粘贴整个代码。 – jpmelos

1

AHA!我相信我已经知道了。我有完全相同的问题。确保你喜欢self.rbv=tk.IntVar(master) #or 'root' or whatever you are using)分配的主子IntVar:

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),你会看到它打印正确改变的值!