-
Book Overview & Buying
-
Table Of Contents
Python GUI Programming Cookbook, Second Edition - Second Edition
By :
Python is a very powerful programming language. It ships with the built-in tkinter module. In only a few lines of code (four, to be precise) we can build our first Python GUI.
To follow this recipe, a working Python development environment is a prerequisite. The IDLE GUI, which ships with Python, is enough to start. IDLE was built using tkinter!
Here are the four lines of First_GUI.py required to create the resulting GUI:

Execute this code and admire the result:

In line nine, we import the built-in tkinter module and alias it as tk to simplify our Python code. In line 12, we create an instance of the Tk class by calling its constructor (the parentheses appended to Tk turns the class into an instance). We are using the alias tk, so we don't have to use the longer word tkinter. We are assigning the class instance to a variable named win (short for a window). As Python is a dynamically typed language, we did not have to declare this variable before assigning to it, and we did not have to give it a specific type. Python infers the type from the assignment of this statement. Python is a strongly typed language, so every variable always has a type. We just don't have to specify its type beforehand like in other languages. This makes Python a very powerful and productive language to program in.
A little note about classes and types:
class keyword instead of the def keyword.class AClass(object): print('Hello from AClass') class_instance = AClass()Now, the variable, class_instance, is of the AClass type. If this sounds confusing, do not worry. We will cover OOP in the coming chapters.In line 15, we use the instance variable (win) of the class to give our window a title via the title property. In line 20, we start the window's event loop by calling the mainloop method on the class instance, win. Up to this point in our code, we created an instance and set one property, but the GUI will not be displayed until we start the main event loop.
win.mainloop() in the preceding code). The event loop ends when the user clicks the red X button or a widget that we have programmed to end our GUI. When the event loop ends, our GUI also ends.This recipe used a minimum amount of Python code to create our first GUI program. However, throughout this book we will use OOP when it makes sense.