How it works...

In lines 75-77, we create some module-level global variables which we will use in the creation of each radio button as well as in the callback function that creates the action of changing the background color of the main form (using the instance variable win).

We are using global variables to make it easier to change the code. By assigning the name of the color to a variable and using this variable in several places, we can easily experiment with different colors. Instead of doing a global search-and-replace of a hardcoded string (which is prone to errors), we just need to change one line of code and everything else will work. This is known as the DRY principle, which stands for Don't Repeat Yourself. This is an OOP concept which we will use in the later recipes of the book.

The names of the colors we are assigning to the variables (COLOR1, COLOR2 ...) are tkinter keywords (technically, they are symbolic names). If we use names that are not tkinter color keywords, then the code will not work.

Line 80 is the callback function that changes the background of our main form (win) depending upon the user's selection.

In line 87 we create a tk.IntVar variable. What is important about this is that we create only one variable to be used by all three radio buttons. As can be seen from the screenshot, no matter which Radiobutton we select, all the others will automatically be unselected for us.

Lines 89 to 96 create the three radio buttons, assigning them to the main form, passing in the variable to be used in the callback function that creates the action of changing the background of our main window.

While this is the first recipe that changes the color of a widget, quite honestly, it looks a bit ugly. A large portion of the following recipes in this book explain how to make our GUI look truly amazing.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134