Getting Started with Creating Desktop Apps with Python-Let's Make an Obesity Determination Tool with Tkinter
Python comes standard with a library called Tkinter that creates Windows / macOS / Linux desktop apps. Using this library, you can create apps with GUI such as buttons and editors. This time, I will introduce how to develop a desktop application. As an example of creation, let's create a BMI calculation tool that determines the degree of obesity. What we're creating here is a tool that displays your BMI and obesity when you enter your height and weight.
What is a desktop app?
By the way, what is a "desktop app"? It is an application that runs on a personal computer such as Windows and macOS. Nowadays, when we talk about apps, we are increasingly referring to apps that target smartphones. Therefore, in contrast to smartphone apps, apps that run on a personal computer are called "desktop apps."
There are several libraries for creating desktop apps in Python. "Tkinter" that comes standard with Python, "Kivy" that is popular for cross-platform, "wxPython" that uses a toolkit called wxWidgets, "PyQt" that uses a toolkit called Qt, and so on. Here, let's introduce how to use the easy-to-use library "Tkinter".
Let's check if Tkinter can be used
Although "Tkinter" is a library that comes standard with Python, it uses a GUI library called "Tcl / Tk" internally, and Tcl / Tk is required to use Tkinter. However, installing Python should also install the Tcl / Tk libraries from the beginning.
However, there is a possibility that Tck / Tk is not included for some reason during installation, so let's check if it works.
In this series, I keep in mind that one of the Python distributions, Anaconda, is installed. If you haven't installed it, please refer to here to install it.
On Windows, launch [Anaconda3> Anaconda Prompt] from the Windows menu. On macOS, start Terminal.app. Then run the following command.
python -m tkinter
If the installation is successful, the Tcl / Tk window will be displayed as shown below.
Python is compatible with Windows / macOS / Linux, but programs using Tkinter can run in much the same way.
However, when I ran this test program on macOS, the characters on the button were cut off. By making large adjustments to the window with the mouse, it appeared as if it were running on Windows. If you want to support multiple operating systems, you will need to allow some room in the layout.
Also, if you get an error and the window doesn't appear, Tcl / Tk may not be installed. You can reinstall Python or download it from ActiveState.
The simplest Tkinter program
Now let's create the simplest Tkinter program. Below is a very basic program that just displays a Tkinter window.
# Tkinterのライブラリを取り込む --- (*1)import tkinter as tk# ウィンドウを作成 --- (*2)win = tk.Tk()win.title("Hello, World!") # タイトルwin.geometry("400x300") # サイズ# ウィンドウを動かす --- (*3)win.mainloop()
Save the above program as "hello_tk.py". Then, when you execute the following command from the command line, a window titled "Hello, World!" Is displayed as shown below.
Let's check the program. In (* 1), the tkinter library is imported. In Python 3.x, the official library name is to write "tkinter" in all lowercase letters. In Python2, only the first letter was capitalized as "Tkinter". Please note that many of the Tkinter materials on the net are from Python 2 and are old.
In the (* 2) part of the program, a window is created and the title and size are specified. Then, in the part (* 3), the main loop is executed so that the window can respond to mouse operations and the like. This line is important for desktop apps that use Tkinter. Don't forget to write it.
Let's use labels, text boxes and buttons
In a program that uses a window, the appearance of the program is constructed by arranging text boxes and labels on the window.
The following is an example of utilizing Label, Entry, and Button.
Let's create a simple program that displays a greeting with a name when you write a name in a text box and press the OK button. Save the following program as "gui.py".
import tkinter as tkfrom tkinter import messagebox as mbox# ウィンドウを作成 --- (*1)win = tk.Tk()win.geometry("500x250") # サイズを指定# 部品を作成 --- (*2)# ラベルを作成label = tk.Label(win, text='名前は?')label.pack()# テキストボックスを作成text = tk.Entry(win)text.pack()text.insert(tk.END, 'クジラ') # 初期値を指定# OKボタンを押した時 --- (*3)def ok_click(): # テキストボックスの内容を得る s = text.get() # ダイアログを表示 mbox.showinfo('挨拶', s + 'さん、こんにちは!')# ボタンを作成 --- (*4)okButton = tk.Button(win, text='OK', command=ok_click)okButton.pack()# ウィンドウを動かすwin.mainloop()
Running "python gui.py" on the command line will run the program in the table below.
Let's check the program. In the part (* 1), create a window.
Then, in the part (* 2), create a label or a text box. Writing tk.Label (...) or tk.Button creates parts such as labels and buttons. Then, if you write pack (), you can place the created parts on the window.
(* 3) describes the processing when the button is pressed. Here, the contents of the text box created in (* 2) are acquired and displayed in the message box as "Hello **-san!".
In the last (* 4) part, create a button and place the button in the window. I also specified that the ok_click function should be executed when clicked.
In this way, in a program that uses windows, the process does not flow straight from top to bottom, but what happens when a button is pressed and what happens when a keyboard is pressed. It tends to be more complicated than a normal program, so get in the habit of organizing and writing it.
Let's make an obesity judgment program
Now that you know how to use Tkinter, let's create an obesity determination program.
import tkinter as tk# ボタンを押したときの処理 --- (*1)def calc_bmi(): # BMIを計算 h = float(textHeight.get()) / 100 w = float(textWeight.get()) bmi = w / h ** 2 rw = h ** 2 * 22 per = int(w / rw * 100) - 100 # 結果をラベルに表示 s = "肥満 {0}% (bmi={1})".format(per, bmi) labelResult['text'] = s# ウィンドウを作成 --- (*2)win = tk.Tk()win.title("肥満判定")win.geometry("500x250")# 部品を作成 --- (*3)labelHeight = tk.Label(win, text=u'身長(cm):')labelHeight.pack()textHeight = tk.Entry(win)textHeight.insert(tk.END, '160')textHeight.pack()labelWeight = tk.Label(win, text=u'体重(kg):')labelWeight.pack()textWeight = tk.Entry(win)textWeight.insert(tk.END, '70')textWeight.pack()labelResult = tk.Label(win, text=u'---')labelResult.pack()calcButton = tk.Button(win, text=u'計算')calcButton["command"] = calc_bmicalcButton.pack()# ウィンドウを動かすwin.mainloop()
To run the program, run "python bmi.py" on the command line. The program is executed as follows. Then, enter your height and weight and click the "Calculate" button to display the obesity and BMI values.
Let's check the program. The (* 1) part of the program describes the processing when the calculation button is pressed. Here, the height and weight values entered in the text box are acquired and the BMI is calculated. Then, the calculation result is displayed on the label.
Then, in the part (* 2), a window is created, and in (* 3), a part is created and placed on the window. Here, we will create labels and text boxes for height and weight, respectively, and also create labels and calculation buttons to display the results. And I specified to call calc_bmi when the calculate button clicked.
summary
As mentioned above, this time I introduced how to use the desktop application using Tkinter. As introduced here, Python makes it easy to create desktop apps that use buttons and text boxes. It's convenient for creating your own tools. You can make various things depending on your ideas, such as an estimation tool and a launcher that executes routine processing.
Freestyle programmer. At Whale Land, we are working to convey the joy of programming. Representative works include the Japanese programming language "Nadeshiko" and the text music "Sakura". Received the 2001 Online Software Award, the 2004 Mitou Youth Super Creator Certification, and the 2010 OSS Contribution Award. He has also written many technical books.