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

1) I need to install one of my three ttk.Radiobuttons activated by default when I launch my gui application.
How to do it?

2) I also need to check if one of my ttk.Radiobuttons has been activated / clicked by the user.
How to 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) 
+6
source share
4 answers

use self.my_var.set(1) to set the radio camera with text='5' as the standard RadioButton.

To get the selected, you must call the 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" 
+13
source

As for your first question, a convenient and easy way is to invoke method:

 rb2.invoke() 

Note that this also launches any command associated with this button.

See the Ttk :: radiobutton invoke documentation.

+7
source

I just add something to Gogo’s answer, but I can’t comment because I don’t have enough reputation.

Add self.my_var=tk.IntVar() before the radio buttons or your program recognize this variable. see Class Variables for more information.

for example, in my case I need StringVar (): this works for python 3. * change tkinter to tkinter for python 2 (I'm not 100% sure)

 import tkinter as tk from tkinter import ttk class XFile_Page(tk.Frame): ... self.joinType = tk.StringVar() self.rbLeft = ttk.Radiobutton(self.frameRadioButtons, text='left', variable=self.joinType, value='left',command=self.RadioBtnSelected) self.rbRight = ttk.Radiobutton(self.frameRadioButtons, text='right', variable=self.joinType, value='right',command=self.RadioBtnSelected) self.rbLeft.grid(row=0) self.rbRight.grid(row=1) #select the rbLeft radiobutton self.rbLeft.invoke() def RadioBtnSelected(self): print(self.joinType.get()) 
+1
source

You can use rb1.state['selected'] to set both rb1 and self.my_var.get() by default to get the value (i.e. text variable) of the radio.

0
source

Source: https://habr.com/ru/post/953525/


All Articles