[Tutor] How to display radiobutton window with no buttons selected?

boB Stepp robertvstepp at gmail.com
Tue Apr 25 07:39:11 EDT 2017


On Tue, Apr 25, 2017 at 2:01 AM, Peter Otten <__peter__ at web.de> wrote:
> boB Stepp wrote:
>
>> Win7-64bit, Python 3.6.1
>>
>> When I run the following code, the radiobutton window initially
>> displays with *all* buttons apparently selected.  However, when the
>> "Status" button is clicked on, the status is as expected, an empty
>> string for the checked_radiobutton StringVar().
>>
>>
> ================================================================================
>> #!/usr/bin/env python3
>>
>> import tkinter as tk
>>
>> root = tk.Tk()
>>
>> # Report option selected:
>> def status():
>>     print('You selected the radiobutton:  %s' % checked_radiobutton.get())
>>     print()
>>
>> languages = ('Perl', 'JavaScript', 'PHP', 'Python 2', 'Python 3')
>>
>> # Create new variable object to keep track of checked radiobutton:
>> checked_radiobutton = tk.StringVar()
>>
>> for language in languages:
>>     # Create new radiobutton:
>>     tk.Radiobutton(root, text=language, variable=checked_radiobutton,
>>             value=language).pack(anchor='w')
>>
>> checked_radiobutton.set('')
>>
>> tk.Button(root, text='Status', command=status).pack(fill='x')
>>
>> root.mainloop()
>>
> ================================================================================
>>
>> I wish the displayed window to initially display with no button
>> selected.  What am I missing here?
>
> It looks like the empty string is special. On my (linux) system all buttons
> appear grayed (while a selected button would be black). Any other string
> should give the desired result, probably because every button "thinks" that
> another button is currently selected.

Interesting.  What you suggest indeed works to create the display I
desired, no radiobuttons selected; however, it does have the undesired
side effect that the status() function reports that value.  So it
looks like the best solution is to set checked_radiobutton to ' ', a
single space.  It is still there in the status() printout, but it does
not look like anything is there.  As this is a toy example, I am not
too concerned.  In something I intended to use, I would probably be
setting a default value for one of the buttons anyway.

Thanks, Peter!

-- 
boB


More information about the Tutor mailing list