Give a radio button a default value in tkinter python
24,487
You can provide an initial value for your StringVar like this:
self.who_goes_first = tkinter.StringVar(None, "B")
or you can simply set the StringVar to a value you want at any time, which will update the radio buttons:
self.who_goes_first.set("B")
Author by
code kid
Updated on July 09, 2022Comments
-
code kid almost 2 years
I'm working on creating a settings window and and I can't figure out how to set a default value for a radio button. I would like the window to start with black checked and if the user does not click on either button a 'B' value would still be returned. Thanks for the help.
import tkinter from tkinter import ttk class Test: def __init__(self): self.root_window = tkinter.Tk() #create who goes first variable self.who_goes_first = tkinter.StringVar() #black radio button self._who_goes_first_radiobutton = ttk.Radiobutton( self.root_window, text = 'Black', variable = self.who_goes_first, value = 'B') self._who_goes_first_radiobutton.grid(row=0, column=1) #white radio button self._who_goes_first_radiobutton = ttk.Radiobutton( self.root_window, text = 'White', variable = self.who_goes_first, value = 'W') self._who_goes_first_radiobutton.grid(row=1, column=1) def start(self) -> None: self.root_window.mainloop() if __name__ == '__main__': game = Test() game.start()