当前位置:网站首页>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笔记本周期性闪屏故障
- Matlab learning notes
- 在jupyter中实现实时协同是一种什么体验
- Summary of being a microservice R & D Engineer in the past year
- tensorflow 1.14指定gpu运行设置
- Dell Notebook Periodic Flash Screen Fault
- Attention SLAM:一種從人類注意中學習的視覺單目SLAM
- Deep learning environment configuration jupyter notebook
- Markov decision process
- AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
猜你喜欢
学习光线跟踪一样的自3D表征Ego3RT
Chapter II proxy and cookies of urllib Library
Set (generic & list & Set & custom sort)
Chenglian premium products has completed the first step to enter the international capital market by taking shares in halber international
Installation and testing of pyflink
Threejs image deformation enlarge full screen animation JS special effect
Mujoco Jacobi - inverse motion - sensor
C9 colleges and universities, doctoral students make a statement of nature!
Equals() and hashcode()
【批处理DOS-CMD命令-汇总和小结】-字符串搜索、查找、筛选命令(find、findstr),Find和findstr的区别和辨析
随机推荐
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
pyflink的安装和测试
View remote test data and records anytime, anywhere -- ipehub2 and ipemotion app
Attention slam: a visual monocular slam that learns from human attention
【JokerのZYNQ7020】AXI_ EMC。
Dell Notebook Periodic Flash Screen Fault
Equals() and hashcode()
Policy Gradient Methods
Levels - UE5中的暴雨效果
[C language] dynamic address book
Article management system based on SSM framework
Summary of being a microservice R & D Engineer in the past year
第六篇,STM32脉冲宽度调制(PWM)编程
《安富莱嵌入式周报》第272期:2022.06.27--2022.07.03
再聊聊我常用的15个数据源网站
C Primer Plus Chapter 14 (structure and other data forms)
tensorflow 1.14指定gpu运行设置
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
第五篇,STM32系统定时器和通用定时器编程
[Batch dos - cmd Command - Summary and Summary] - String search, find, Filter Commands (FIND, findstr), differentiation and Analysis of Find and findstr