SoFunction
Updated on 2024-10-30

A simple tutorial to get started with python Tkinter

We will write a program that converts feet to meters. Through this program, we will learn how a real utility program is designed and written, and we will get a basic look at what the inside of a Tk program looks like. It is not necessary to know everything about the program; more details will be given in later chapters. This section only requires an understanding of how to design and write a Tk GUI program.

devise

We're going to write a simple GUI tool that converts feet to meters, which in our experience should look like the following:

The program will have an input box to enter the number of feet, a display box to show the converted number, several text areas to display prompt characters, and, just as importantly, a conversion trigger button.

It's easy to see that the program is roughly divided into three rows and three columns, which is important in terms of geometry management (for controlling the size and position of the components), which we'll talk about in a later section.

coding

from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(())
        ((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass

root = Tk()
("Feet to Meters")
mainframe = (root, padding="3 3 15 15")
(column=0, row=0, sticky=(N, W, E, S))
(0, weight=1)
(0, weight=1)

feet = StringVar()
meters = StringVar()

feet_entry = (mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
(mainframe, text="Conversion.", command=calculate).grid(column=3, row=3, sticky=W)

(mainframe, text="Feet.").grid(column=3, row=1, sticky=W)
(mainframe, text="Equal to.").grid(column=1, row=2, sticky=E)
(mainframe, text="Rice.").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

feet_entry.focus()
('<Return>', calculate)

()

It'll end up looking like this.

explain step by step

To write a Tk program, we first need to introduce the Tkinter module.

from tkinter import *
from tkinter import ttk

These two lines tell Python that our program needs both modules. First, tkinter is a standard package for Tk, and when it is loaded, it also causes the Tk library to be loaded on your system. Second, tkk is a new addition in Tk 8.5 that provides access to the set of Tk-themed widgets introduced in Tk 8.5. The basic idea is to keep the code that implements the behavior of the widgets as separate as possible from the code that implements their appearance, and we won't go into that in depth here.

It's worth noting that we've imported all the functions from the tkinter module, so we can call all the functions in tkinter directly without prefixing them. However, we have only imported the ttk module, so we should add the ttk prefix when using functions from the ttk module.

If you're modifying old code to new code, you'll notice that Tkinter's name has changed from uppercase to lowercase tkinter, a change that began with Python 3.0.

root = Tk()
("Feet to Meters")
mainframe = (root, padding="3 3 15 15")
(column=0, row=0, sticky=(N, W, E, S))
(0, weight=1)
(0, weight=1)

The calculate function will be explained later, but it's up front because it will be called later in many statements.

The root = Tk() statement builds a main window, also known as the root window. Use ("title") to give the window a name. (root, padding="3 3 15 15") creates a frame that is divided into three rows and three columns of 15 pixels. we place this frame in the root window, except that all of our components are placed in this frame instead of the root window.

Generally speaking, we can put all the components (Widget) into the root window, but the background of the main window may not match with the components we add, at this time, we add an intermediate frame (Frame), the components will be put into this intermediate frame to ensure that the content and the background match.

columncoonfigure and rowconfigure tell Tk that when the main window is re-sized, then the Frame frames on top of that should also change to take up the extra space.

feet = StringVar()
meters = StringVar()
feet_entry = (mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
(mainframe, text="Conversion.", command=calculate).grid(column=3, row=3, sticky=W)

The above statements create three components on the frame (mainframe), the input box, the output area (Label, which holds the result of the conversion), and the conversion button.

For each component (Widget), we need to do two things:

  1. establish
  2. place

They are all classes in the ttk module. When creating them, we specify the incoming parameters: the frame to be placed, the size, the characters in the buttons, and so on. As for the meaning of textvariable, it refers to the variable associated with the value in this input or output frame, which is an object of type StringVar.

We use grid for geometry management, meaning where the component will be placed (which row, which column), sticky specifies how the component will be lined up in the grid cell to which it is assigned, and E, W, S, N means east, west, south, north, and south, which is similar to centering, leaning to the left, leaning to the right, and so on in a text editor.

(mainframe, text="Feet.").grid(column=3, row=1, sticky=W)
(mainframe, text="Equal to.").grid(column=1, row=2, sticky=E)
(mainframe, text="Rice.").grid(column=3, row=2, sticky=W)

The above three lines create three text labels with the specified contents and place them in the specified locations.

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)
feet_entry.focus()
('<Return>', calculate)

These four lines of code do a nice job of wrapping up our graphic.

The first two lines of code iterate through all the components placed in the mainframe and add some borders around them so that they don't all fit together. It would be possible to iterate through the components individually and set them up one by one, but that's not a convenient way to do it.

The third line of code tells Tk to focus the cursor on the input box while the program is running so that the user doesn't have to click on the input box one more time.

The fourth line of code tells Tk to call the calculate function when the user presses Return (Enter in Windows). This is the same as calling the calculate function when the button is pressed.

def calculate(*args):
    try:
        value = float(())
        ((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass

Here we have defined a calculate function call that will be called when the Return, Enter (Windows), or Convert button is pressed. It takes the value entered by the user from the input box and after converting it to a value in meters, sets the value in the input box to the correct result.

As you can see, the calculate function gets feet and sets meters to change the values displayed in their respective Entry and Label boxes. When the user's input is changed, the value of the corresponding feet is changed to the corresponding input value, and when the meters are changed, the value displayed in the corresponding Label is also changed. This is why when defining feet_entry and label, you should also specify the value of textvariable, which should be a StringVar object. As in the following example:

feet = StringVar()
meters = StringVar()
feet_entry = (mainframe, width=7, textvariable=feet)
(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
()

The last sentence tells Tk to enter the event loop, which is necessary to get something running.

Above is the details of python Tkinter's simple introductory tutorial, for more information about python Tkinter's introductory tutorial, please pay attention to my other related articles!