This article discusses creating a GUI (Graphical User Interface) program in Python. GUI programs present one or more windows for the user to interface with.
There are multiple ways to create a GUI in Python. This article will focus on using the TKinter library, which is a set of pre-packaged Python functions to utilize windows and window elements.
Most GUI programs are very similar in how they are configured. Here is the general program flow:
- import the TKinter library
- create one or more classes for each frame or window
- define all the UI elements inside the frame class
- define the first or main window
- activate the main window
TKinter programs use a mixture of libraries, classes and functions. A window in Python is referred to as a frame. A frame contains user-interface (UI) elements, such as labels, text boxes, buttons, and images. A frame may also contain other frames. Code-wise, a frame is defined as a class. It is common to define the title and frame or window size inside the frame class. It is also common to include in the frame class all labels, text boxes, buttons, images, and other elements.
Here is an example of a Python program window:
This screen shot identities the components of that frame (window), including the title, width and height, and the label placed on the left side of the frame:
Now, the code that draws that frame. The program uses a class named "Frame1" to define that window in the Python program. The code displayed below is only the class definition that defines the frame. The full program will be displayed later.
GUI coding involves "objects". This is part of what is called OOP (Object Oriented Programming). Objects have attributes, such as size, color and text. They also have behaviors, meaning they act in certain ways. A button, for example, often changes shape slightly to show it was clicked. Lastly, objects can trigger events. When a button is clicked, it usually calls a function to do something.
The first object in this example is Frame1. Frame1 is declared as a class, which defines an object in languages like Python. The frame has several attributes that are set, including the title and geometry (size and position). For now, we'll skip the specifics of the Frame1 __init__, other than to note that the code gives the frame an alias of "self".
Objects on the UI (user interface), such as labels, text boxes, and buttons, are called elements. To display elements on a frame we must declare the element, including the object type (label, text box, button), and any attributes to control how it is presented. We must also place the object in a frame. In the example above, a single element was defined and placed on Frame1. Here is the label declaration:
An element is a variable. This is the syntax:
Label 2 above is placed at (x=120,y=60). In other words, on the same vertical line, 60 pixels from the top, and farther to the right from Label 1, 120 pixels from the left edge.
Next article: Text Boxes & Buttons.