Tkinter: How to set ttk.Radiobutton activated and get its value?

minerals picture minerals · Sep 10, 2013 · Viewed 29k times · Source

1) I need to set one of my three ttk.Radiobuttons activated by default when I start my gui app.
How do I do it?

2) I also need to check if one of my ttk.Radiobuttons was activated/clicked by the user.
How do I do it?

rb1 = ttk.Radiobutton(self.frame, text='5', variable=self.my_var, value=5)
rb2 = ttk.Radiobutton(self.frame, text='10', variable=self.my_var, value=10)
rb3 = ttk.Radiobutton(self.frame, text='15', variable=self.my_var, value=15)
self.rb1.grid(row=0)
self.rb2.grid(row=1)
self.rb3.grid(row=2)

Answer

Alok picture Alok · Sep 24, 2013

use self.my_var.set(1) to set the radiobutton with text='5' as the default RadioButton.

To get the selected one you have to call a function

rb1 = ttk.Radiobutton(self.frame, text='5', variable=self.my_var, value=5,command=self.selected)
rb2 = ttk.Radiobutton(self.frame, text='10', variable=self.my_var, value=10,command=self.selected)
rb3 = ttk.Radiobutton(self.frame, text='15', variable=self.my_var, value=15,command=self.selected)
self.rb1.grid(row=0)
self.rb2.grid(row=1)
self.rb3.grid(row=2)

def selected(self):
     if self.my_var.get()==5:
        "do something"
     elif self.my_var.get()==10:
        "do something"
     else:
        "do something"