Skip to main content

My First Window dissected

Let's look at the three lines of My First Window code. The first line is:


from tkinter import *


This imports the tkinter module. You have to import it if you want to use the widgets the module provides.


How else would you use them if you did not tell your Python that you will be using it? So, you import it.


This syntax which we used in our My First Window is the worst possible way to do it.


from tkinter import *


That works. It is short and sweet. Yet, it is horrible. I could explain why but once again I do not feel like reinventing. Read this and this to find out why it is such a bad idea to use that syntax.


Building a blog is not only a great way to teach people but it really helps you learn what you are doing because every-time you are about to teach something you have all these possible questions readers might ask pop up into your head. Then, you search for the answers to learn to teach. You also make yourself a great future resource of what you learned in case you forget. It saves you time from having to research the topics you did not know about since they are all in one place. 


Sorry for that tangent. But I think people need to learn to do things for themselves more than for others and enjoy what they do. If people do not like it, who cares.


For now we will stick to


from tkinter import *


We will improve on it later in terms of syntax.


Let's create the Window



The next line reads


root = Tk()


You can think of this as the way of creating the main window. Root refers to your main window. You can name it anything you like. You could have written:


mainwindow = Tk()


Or


rootwindow = Tk()



The technical detail of what is going on is explained here.


For our purposes all we need to know is that we have imported the tkinter module and created a window by doing what we did.


Put the Window in an endless loop


The final piece of code is


mainloop()


This is an infinite loop. It keeps looping. It waits for events. GUI applications are connected to events. A mouse click is an event.


When you press a keyboard key that triggers an event. When you raise the mouse release a clicked mouse button, that is an event.


The mainloop() catches these events and then you can program your application to do what you want it to do when an event takes place.


The loop ends when the user closes the Window.


So, there you have it.



You imported the module you needed to build your first window.

You created the window.

You put your program into a loop so that you can catch events like clicks and all to do what you want to do.



That is really what GUI programming is all about. You catch the events, which is what the user does with the mouse and keyboard, and translate them into actions you would like your program to perform.


Comments