Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give a radio button a default value in tkinter python

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()
like image 946
code kid Avatar asked Mar 16 '17 21:03

code kid


1 Answers

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")
like image 89
Novel Avatar answered Nov 08 '22 23:11

Novel