Skip to content Skip to sidebar Skip to footer

Tkinter Radiobutton Not Updating Variable

--UPDATE: I changed variable=self.optionVal.get() to variable=self.optionVal But nothing changed.Also I wonder why it automatically call self.selected while compiling? ----Orig

Solution 1:

AHA! I beleive I've figured it out. I had the exact same issue. make sure you are assigning a master to the IntVar like self.rbv=tk.IntVar(master) #or 'root' or whatever you are using):

import Tkinter as tk
import ttk

classMy_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')

    defonRadioChange(self,event=None):
        print self.rbv.get()

root=tk.Tk()
gui=My_GUI(root)
root.mainloop()

try running that, click the different buttons (they are radiobuttons but with indicatoron=False) and you will see it prints correctly changed values!

Solution 2:

You're very close. Just take out the .get() from self.optionVal.get(). The Radiobutton constructor is expecting a traced variable, you're giving it the result of evaluating that variable instead.

Solution 3:

You need to:

  1. Remove the .get() from the variable=self.optionVal argument in the constructor the button. You want to pass the variable, not the evaluated value of the variable; and
  2. Remove the parenthesis from command=self.selected() and use command=self.selected instead. The parenthesis says "call this function now and use the return value as the callback". Instead, you want to use the function itself as the callback. To better understand this, you need to study closures: a function can return a function (and, if that was the case, that would be used as your callback).

EDIT: A quick reminder, also: Python is not compiled, but interpreted. Your callback is being called while the script is being interpreted.

Post a Comment for "Tkinter Radiobutton Not Updating Variable"