简体   繁体   中英

tkinter radio buttons are selected by default

I am using radio button selection to change a label widget in my window, I've just written this code to save myself having to write essentially the same thing four times, but when it runs it creates the radio buttons as checked by default.

单选按钮调皮的图像

Here is the code in question:

# At the top of the method
radio_text = ['The Tivoli Theatre', 'Brisbane City', 'Suncorp Stadium']
radio_buttons_list = []
# Radio buttons are stored in a frame, according to a grid layout. When clicked they call the Generate_Event_Info method and 
# the value passed along corrosponds to a case in the method. Production version will use database input to generate responses.
self.v = IntVar() 
for i in range(len(radio_text)):
    radio_buttons_list.append(Radiobutton(self.radio_options_frame, text=radio_text[i], font=self.style, bg=self.bg_colour, variable=self.v, value=0, command=self.Generate_Event_Info).grid(row=i, column=0, pady=5, sticky='w'))

Sorry for the extremely long line at the end there, you can see why I wanted to take care of it with a loop. When I create them one by one without a loop there isn't an issue, but the code is a mess (not the end of the world but I'm still curious what's causing this issue). Any help would be much appreciated!

I fixed it. Gonna leave the question up but I'm posting an answer here. Turns out I forgot to assign the value to the loop index. I changed it and still had an issue where the widget was auto-selecting the first option as v has a default value of 0. I used the set() function to set the v variable to -1 and that fixed it! Here is the remedied code with asterisks next to the changed parts:

self.v = IntVar() 
self.v.set(-1)**
for i in range(len(radio_text)):
    radio_buttons_list.append(Radiobutton(self.radio_options_frame, text=radio_text[i], font=self.style, bg=self.bg_colour, variable=self.v, value=i**, command=self.Generate_Event_Info).grid(row=i, column=0, pady=5, sticky='w'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM