当前位置:网站首页>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()
边栏推荐
- 什么是时间
- 深度学习简史(一)
- 城联优品入股浩柏国际进军国际资本市场,已完成第一步
- 【YoloV5 6.0|6.1 部署 TensorRT到torchserve】环境搭建|模型转换|engine模型部署(详细的packet文件编写方法)
- fastDFS数据迁移操作记录
- [user defined type] structure, union, enumeration
- The printf function is realized through the serial port, and the serial port data reception is realized by interrupt
- from .cv2 import * ImportError: libGL.so.1: cannot open shared object file: No such file or direc
- Advanced learning of MySQL -- basics -- multi table query -- subquery
- Web project com mysql. cj. jdbc. Driver and com mysql. jdbc. Driver differences
猜你喜欢
第五篇,STM32系统定时器和通用定时器编程
[Niuke classic question 01] bit operation
Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
Batch obtain the latitude coordinates of all administrative regions in China (to the county level)
Explain in detail the matrix normalization function normalize() of OpenCV [norm or value range of the scoped matrix (normalization)], and attach norm_ Example code in the case of minmax
Equals() and hashcode()
做微服务研发工程师的一年来的总结
重上吹麻滩——段芝堂创始人翟立冬游记
Dell筆記本周期性閃屏故障
【批处理DOS-CMD命令-汇总和小结】-跳转、循环、条件命令(goto、errorlevel、if、for[读取、切分、提取字符串]、)cmd命令错误汇总,cmd错误
随机推荐
[software reverse - solve flag] memory acquisition, inverse transformation operation, linear transformation, constraint solving
Dr selection of OSPF configuration for Huawei devices
Summary of being a microservice R & D Engineer in the past year
A brief history of deep learning (II)
【JokerのZYNQ7020】AXI_EMC。
Threejs image deformation enlarge full screen animation JS special effect
Three methods to realize JS asynchronous loading
Common shortcuts to idea
stm32F407-------SPI通信
Chenglian premium products has completed the first step to enter the international capital market by taking shares in halber international
Article management system based on SSM framework
深度学习之线性代数
pyflink的安装和测试
Explain in detail the implementation of call, apply and bind in JS (source code implementation)
[C language] dynamic address book
Data sharing of the 835 postgraduate entrance examination of software engineering in Hainan University in 23
The printf function is realized through the serial port, and the serial port data reception is realized by interrupt
【软件逆向-自动化】逆向工具大全
Idea automatically imports and deletes package settings
ActiveReportsJS 3.1中文版|||ActiveReportsJS 3.1英文版