当前位置:网站首页>Make a simple graphical interface with Tkinter
Make a simple graphical interface with Tkinter
2022-07-07 00:57:00 【A big pigeon】
tkinter brief introduction
tkinter yes Python Bring one with you GUI package . The advantages and disadvantages are obvious :
advantage : Simple 、 Fast 、 No installation required
shortcoming : Interface Retro , Lack of support for some complex functions
( Be careful ,Python2 Of tkinter The name is Tkinter, We won't discuss it )
start-up tkinter
Enter at the command line
python -m tkinter
It will pop up a tkinter window :
The top version is 8.6, Click on click me! It seems that nothing will happen , Click on QUIT You can quit .
Let's introduce tkinter Simple usage , More can go to GUI What is it? (biancheng.net) or
Python GUI Programming (Tkinter) | Novice tutorial (runoob.com) or Tkinter 8.5 reference: a GUI for Python (tkdocs.com) Study .
tkinter HelloWorld
Use tkinter Create a window , The title is Hello,world.
# -*- coding:utf-8 -*-
import tkinter as tk
# call Tk() Create main window
root_window =tk.Tk()
# Give the main window a name , That's the name of the window
root_window.title('Hello,world')
# Set window size 450x300
root_window.geometry('450x300')
# Turn on the main loop , Keep the window on display
root_window.mainloop()
Import :tkinter
Create main window : root_window =tk.Tk()
Set window properties ( title 、 size ):
root_window.title(‘Hello,world’)
root_window.geometry(‘450x300’)
Turn on the main loop
root_window.mainloop()
tkiner Height calculator
Now let's make a functional tkinter Program .
The end result is as follows : We enter the height , Click calculate . Then the program calculates , Get our height and show it .
So we're up there Helloworld Start making on the basis of the program . First , Let's change the window name to “ Height calculator ”.
root_window.title(' Height calculator ')
Then we need to push the button , Put the prompt message .
# root_window.geometry('450x300') Add... Below ...
# After setting the window , Add the component
tk.Label(root_window, text=" Please enter height ").pack()
cms= StringVar()
tk.Entry(root_window, width=7, textvariable=cms).pack()
tk.Label(root_window, text="cm").pack()
tk.Label(root_window, text=" Your height is ").pack()
result = StringVar()
tk.Label(root_window, textvariable=result).pack()
tk.Label(root_window, text="cm").pack()
B = tk.Button(root_window, text=" Calculation ")
B.pack()
We mainly use three components ,tk.Label
、tk.Entry
and tk.Button
, Respectively represent text labels 、 Input box 、 Button . After creating the component, you need to call .pack() Methods place , Otherwise, it will not appear on the interface .
explain : With this tk.Label For example . Parameter needs to be passed into its parent container ( Here is root_window), Written content (text=“ Please enter height ”). And then call .pack() Method to put it on the window .
tk.Label(root_window, text=" Please enter height ").pack()
We can also make Label The text of is a variable . Now let's create a variable result = StringVar(), And then result As tk.Label Parameters of .
result = StringVar() tk.Label(root_window, textvariable=result).pack()
But after clicking calculate , There will be no action , We also need to bind the click button to the function .
We define functions calculate
To achieve the function , Get the input data first (cmt.get()), Then set the data of the output text (result.set()).
def calculate(*args):
try:
value = float(cms.get())
result.set(value)
except ValueError:
pass
And through command=calculate take calculate Method and click button binding .
B = tk.Button(root_window, text=" Calculation ",command=calculate)
Complete code :
# -*- coding:utf-8 -*-
import tkinter as tk
from tkinter import *
# call Tk() Create main window
root_window = tk.Tk()
# Give the main window a name , That's the name of the window
root_window.title(' Height calculator ')
# Set window size 450x300
root_window.geometry('450x300')
# root_window.geometry('450x300') Add... Below ...
# After setting the window , Add the component
tk.Label(root_window, text=" Please enter height ").pack()
cms = StringVar()
tk.Entry(root_window, width=7, textvariable=cms).pack()
tk.Label(root_window, text="cm").pack()
tk.Label(root_window, text=" Your height is ").pack()
result = StringVar()
tk.Label(root_window, textvariable=result).pack()
tk.Label(root_window, text="cm").pack()
def calculate(*args):
try:
value = float(cms.get())
result.set(value)
except ValueError:
pass
B = tk.Button(root_window, text=" Calculation ", command=calculate)
B.pack()
# Turn on the main loop , Keep the window on display
root_window.mainloop()
In addition to .pack() Place components , Another more flexible way is .grid(row=r,column=0) The way . In this way, the interface is used as a grid , Then place components on the grid .
# After setting the window , Add the component
tk.Label(root_window, text=" Please enter height ",).grid(row=0,column=0)
cms = StringVar()
tk.Entry(root_window, width=7, textvariable=cms).grid(row=0,column=1)
tk.Label(root_window, text="cm").grid(row=0,column=2)
tk.Label(root_window, text=" Your height is ").grid(row=1,column=0)
result = StringVar()
tk.Label(root_window, textvariable=result).grid(row=1,column=1)
tk.Label(root_window, text="cm").grid(row=1,column=2)
def calculate(*args):
try:
value = float(cms.get())
result.set(value)
except ValueError:
pass
B = tk.Button(root_window, text=" Calculation ", command=calculate)
B.grid(row=3,column=3)
Of course , If you think the font is too small , It can also be in font Parameter setting ,font It's a triple ( family, size, style), Namely ( typeface , size , Format ).
tk.Label(root_window, text=" Please enter height ",font=("Courier", 24, "italic"),height=3).grid(row=0,column=0)
tkinter BMI Calculator
Minor modifications , We can make a BMI Calculator :
Code :
# -*- coding:utf-8 -*-
import tkinter as tk
from tkinter import *
# call Tk() Create main window
root_window = tk.Tk()
# Give the main window a name , That's the name of the window
root_window.title('BMI Calculator ')
# Set window size 450x300
root_window.geometry('450x300')
# root_window.geometry('450x300') Add... Below ...
# After setting the window , Add the component
tk.Label(root_window, text=" Please enter height cm",height=3).grid(row=0,column=0)
cms = StringVar()
tk.Entry(root_window, width=7, textvariable=cms).grid(row=0,column=1)
tk.Label(root_window, text="cm").grid(row=0,column=2)
tk.Label(root_window, text=" Please lose your weight kg",height=3).grid(row=1,column=0)
kg = StringVar()
tk.Entry(root_window, width=7, textvariable=kg).grid(row=1,column=1)
tk.Label(root_window, text="kg").grid(row=1,column=2)
tk.Label(root_window, text=" you BMI yes ").grid(row=2,column=0)
result = StringVar()
tk.Label(root_window, textvariable=result).grid(row=2,column=1)
def calculate(*args):
try:
cm_ = float(cms.get())
kg_ = float(kg.get())
value_ = kg_ / ((cm_/100) **2)
value_ = value_.__round__(3)
result.set(value_)
except ValueError:
pass
B = tk.Button(root_window, text=" Calculation ", command=calculate)
B.grid(row=3,column=3)
# Turn on the main loop , Keep the window on display
root_window.mainloop()
边栏推荐
- Dell筆記本周期性閃屏故障
- 代码克隆的优缺点
- String comparison in batch file - string comparison in batch file
- Js+svg love diffusion animation JS special effects
- Deep understanding of distributed cache design
- Advanced learning of MySQL -- basics -- multi table query -- joint query
- 第七篇,STM32串口通信编程
- Distributed cache
- [user defined type] structure, union, enumeration
- Telerik UI 2022 R2 SP1 Retail-Not Crack
猜你喜欢
Deep learning environment configuration jupyter notebook
Deeply explore the compilation and pile insertion technology (IV. ASM exploration)
Configuring OSPF basic functions for Huawei devices
【YoloV5 6.0|6.1 部署 TensorRT到torchserve】环境搭建|模型转换|engine模型部署(详细的packet文件编写方法)
Zynq transplant ucosiii
equals()与hashCode()
Mujoco Jacobi - inverse motion - sensor
C9 colleges and universities, doctoral students make a statement of nature!
深入探索编译插桩技术(四、ASM 探秘)
Batch obtain the latitude coordinates of all administrative regions in China (to the county level)
随机推荐
Learning notes 5: ram and ROM
The printf function is realized through the serial port, and the serial port data reception is realized by interrupt
Data sharing of the 835 postgraduate entrance examination of software engineering in Hainan University in 23
Telerik UI 2022 R2 SP1 Retail-Not Crack
Building a dream in the digital era, the Xi'an station of the city chain science and Technology Strategy Summit ended smoothly
alexnet实验偶遇:loss nan, train acc 0.100, test acc 0.100情况
String comparison in batch file - string comparison in batch file
Chenglian premium products has completed the first step to enter the international capital market by taking shares in halber international
OSPF configuration command of Huawei equipment
C9高校,博士生一作发Nature!
【JokerのZYNQ7020】AXI_EMC。
Address information parsing in one line of code
Quaternion attitude calculation of madgwick
Telerik UI 2022 R2 SP1 Retail-Not Crack
Part IV: STM32 interrupt control programming
.class文件的字节码结构
Configuring OSPF basic functions for Huawei devices
stm32F407-------SPI通信
深度学习之环境配置 jupyter notebook
Web project com mysql. cj. jdbc. Driver and com mysql. jdbc. Driver differences