tk_radiobutton_example.py

tk_radiobutton_example.py This is an important widget.  It’s not too complicated once you grasp how the buttons communicate with the handler.

Basically a button is created with the Radiobutton keyword and I’ve documented the fields starting at line 74.  Note the relation between the ‘value’ or what is passed and the ‘variable’, which is the common name the handler checks for a group of buttons.  That’s how you group them together, with a common ‘variable’, here rb_var.  You can have multiple groups of buttons if you use different variables and handlers. In line 67 rb_var was set to StringVar() (it could be a different type, like IntVar).  This is required.  When any button is pushed the handler, using the rb_var.get() method, grabs the ‘value’ of the selected button and decides what to do with it.  In our example a different message gets printed to the Canvas, depending on the ‘value’ passed in. So for me at first the .get() and the need to assign the variable as StringVar() were not clear, but once you understand that it’s not difficult.

OK, I have some suggested edits to make to show different options.  For sure uncomment lines 32 and 33 to switch from radio button to box button mode.  And set the anchor option for a radio button to ‘center’ just to see how bad that looks, so you’ll never make that mistake again.  Or if you do you’ll know how to fix it. Also uncomment line 69 to see how it’s possible to initialize the buttons so one appears active at start-up.  Then uncomment line 70 to see what I think is the best way to initialize the buttons. You’ve seen the rest of the code before in the previous examples, like the text for the canvas widget, but post here if you have questions. And check out the 38 options available for this widget.  Feel free to try different things.  http://effbot.org/tkinterbook/radiobutton.htm