Tkinter summary of Python GUI - Zhihu

osc_ beahvznj 2021-01-19 16:10:34
tkinter summary python gui zhihu


background

The owner is in use Python In the process of production, everything goes to products , In the middle Tkinter、Flask web、 Wechat applet . Initially, the single Tkinter Can't solve user system 、Flask Lightweight packaging only 、 Wechat apps are subject to wechat system , Play around , Back to Tkinter, Successfully connected the three , So it is necessary to Tkinter Make a summary .

Control size

from tkinter import *
# It's usually measuring tkinter Control , It's in pixels . The following definition Button The horizontal distance between the text and the border of the control is 20 Pixels :
win=Tk()
Button(win,padx=20,text=" close ",command=win.quit).pack()
win.mainloop()
from tkinter import *
# Other units of measurement can also be used , Such as c( centimeter )、m( mm )、i( Inch =2.54cm)、p( spot ,1p = 1 / 72 Inch ). The sample code is as follows :
win=Tk()
Button(win,padx=20,text=" close ",command=win.quit).pack()
Button(win,padx="2c",text=" close ",command=win.quit).pack()
Button(win,padx="8m",text=" close ",command=win.quit).pack()
Button(win,padx="2i",text=" close ",command=win.quit).pack()
Button(win,padx="20p",text=" close ",command=win.quit).pack()
win.mainloop()

Frame

Parameters

Frame(master=None, **options) (class)

master -- Parent component

**options -- Component options , The table below lists the specific meaning and usage of each option in detail :


Options meaning
background 1. Set up Frame Background color of component 2. The default value is specified by the system 3. To prevent updates , You can set the color value to an empty string
bg Follow background equally
borderwidth 1. Appoint Frame The border width of 2. The default value is 0
bd Follow borderwidth equally
class_ The default value is Frame
colormap 1. Some monitors only support 256 color ( Some may be less ), This kind of display usually provides a color map to specify the 256 Color 2. This option allows you to specify the color mapping for the component and its subcomponents 3. By default ,Frame Use the same color mapping as its parent component 4. Use this option , You can use color maps from other windows instead of ( Two windows must be on the same screen and have the same visual characteristics )5. You can also use it directly "new" by Frame Component to assign a new color map 6. Once created Frame Component instance , You can't change the value of this option
container 1. If this option is True, Means that the window will be used as a container , Some other applications will be embedded 2. The default value is False
cursor 1. Specify when the mouse is in Frame The mouse style when it floats over 2. The default value is specified by the system
height 1. Set up Frame Height 2. The default value is 0
highlightbackground 1. Designated as Frame Highlight the color of the border when you don't get the focus 2. The default value is specified by the system , It's usually the standard background color
highlightcolor 1. Designated as Frame Highlight the color of the border when you get the focus 2. The default value is specified by the system
highlightthickness 1. Specify the width of the highlighted border 2. The default value is 0( Without a highlighted border )
padx Horizontal margins
pady Vertical margins
relief 1. Specify border style 2. The default value is "flat"3. In addition, you can set "sunken","raised","groove" or "ridge"4. Be careful , If you want to set the border style , Remember to set up borderwidth or bd The option is not 0, To see the border
takefocus 1. Specifies whether the component accepts input focus ( The user can go through tab The key shifts the focus )2. The default value is False
visual 1. Specify visual information for the new window 2. There is no default value for this option
width 1. Set up Frame Width 2. The default value is 0


import tkinter as tk
master = tk.Tk()
tk.Label(text=" Heavenly King Gedi tiger ").pack()
separator = tk.Frame(height=2, bd=1, relief="sunken")
separator.pack(fill="x", padx=5, pady=5)
tk.Label(text=" Stewed chicken with mushroom ").pack()
master.mainloop()

LabelFrame

Parameters

LabelFrame(master=None, **options) (class)

master -- Parent component

**options -- Component options , The table below lists the specific meaning and usage of each option in detail :


Options meaning
background 1. Set up LabelFrame Background color of component 2. The default value is specified by the system 3. To prevent updates , You can set the color value to an empty string
bg Follow background equally
borderwidth 1. Appoint LabelFrame The border width of 2. The default value is 2 Pixels
bd Follow borderwidth equally
class The default value is LabelFrame
colormap 1. Some monitors only support 256 color ( Some may be less ), This kind of display usually provides a color map to specify the 256 Color 2. This option allows you to specify the color mapping for the component and its subcomponents 3. By default ,Frame Use the same color mapping as its parent component 4. Use this option , You can use color maps from other windows instead of ( Two windows must be on the same screen and have the same visual characteristics )5. You can also use it directly "new" by Frame Component to assign a new color map 6. Once created Frame Component instance , You can't change the value of this option
container 1. If this option is True, Means that the window will be used as a container , Some other applications will be embedded 2. The default value is False
cursor 1. Specify when the mouse is in LabelFrame The mouse style when it floats over 2. The default value is specified by the system
foreground 1. Set up LabelFrame The color of the text 2. The default value is specified by the system
fg Follow foreground equally
font 1. Appoint LabelFrame The font of Chinese text 2. The default value is specified by the system
height 1. Set up LabelFrame Height 2. Unit is pixel
highlightbackground 1. Designated as LabelFrame Highlight the color of the border when you don't get the focus 2. The default value is specified by the system , It's usually the standard background color
highlightcolor 1. Designated as LabelFrame Highlight the color of the border when you get the focus 2. The default value is specified by the system
highlightthickness 1. Specify the width of the highlighted border 2. The default value is 1 or 2 Pixels
labelanchor 1. Control text in LabelFrame The display position of 2. "n", "ne", "e", "se", "s", "sw", "w", "nw", or "center" To locate (ewsn It represents East, West, north, South , Up north down south left West right east )3. The default value is NW
labelwidget 1. Specify a component to replace the default text Label2. If you set this option and text Options , It ignores text The content of the options
padx 1. Appoint FrameLabel Extra spacing in the horizontal direction ( Between the content and the border )2. The default value is 0
pady 1. Appoint FrameLabel Additional spacing in the vertical direction ( Between the content and the border )2. The default value is 0
relief 1. Specify border style 2. The default value is "groove"3. In addition, you can set "flat","sunken","raised" or "ridge"4. Be careful , If you want to set the border style , Remember to set up borderwidth or bd The option is not 0, To see the border
takefocus 1. Specifies whether the component accepts input focus ( The user can go through tab The key shifts the focus )2. The default value is False
text 1. Appoint LabelFrame Displayed text 2. Text can contain line breaks
visual 1. Specify visual information for the new window 2. There is no default value for this option
width 1. Set up LabelFrame Width 2. The default value is 0


import tkinter as tk
master = tk.Tk()
group = tk.LabelFrame(master, text=" Where do you know CSDN?", padx=5, pady=5)
group.pack(padx=10, pady=10)
v = tk.IntVar()
r1 = tk.Radiobutton(group, text=" classmate / Introduction of colleagues ", variable=v, value=1).pack(anchor="w")
r2 = tk.Radiobutton(group, text=" My wife introduces ", variable=v, value=2).pack(anchor="w")
r3 = tk.Radiobutton(group, text=" teacher / The senior introduces ", variable=v, value=3).pack(anchor="w")
master.mainloop()



pack

attribute Attribute analysis remarks other
fill Set whether the component fills horizontally or vertically , contain X、Y、BOTH、NONE fill = X( Fill horizontally )fill = Y( Vertical fill )fill = BOTH( Horizontal and vertical )NONE No fill
expand Set whether the component is expanded , The duty of YES when ,side Invalid option . The component is displayed in the center of the parent container ; if fill The options are BOTH, Then fill in the remaining space of the parent component . It means that a control is in fill That direction , Do you want to assign the blank space to it YES 、NO(1、0) if expand=True perhaps expand=1, It means that fill That direction , Give all the blank space to this control , Make it as full as possible . if expand=False perhaps expand=0, It means that fill That direction , Don't give it when you have time .
side Set the alignment of components LEFT、TOP、RIGHT、BOTTOM The value is left 、 On 、 Right 、 Next
ipadx、ipady Set up x Direction ( perhaps y Direction ) Internal clearance ( Spacing between subcomponents ), It represents the inner margin of a control , The edge of the control and the content of the control ( Words, pictures, etc ) The distance between The value can be set , The default is 0 Non-negative integer , In pixels
padx、pady Set up x Direction ( perhaps y Direction ) The outer gap ( The space between the components juxtaposed with it ), It represents the outer margin of a control , The distance between the edge of the control and the container where the control is located The value can be set , The default is 0 Non-negative integer , In pixels
anchor Anchor options , When the available space is larger than the required size , Decide where the component is placed in the container , It represents how a control is placed in a container , Is it left or right , Up or down N、E、S、W、NW、NE、SW、SE、CENTER( The default value is CENTER) Eight directions and centers


from tkinter import *
# main window 
win = Tk()
# The first form 
frame1 = Frame (win, relief=RAISED, borderwidth=0)
frame1 .pack(side=TOP, fill=BOTH, ipadx=13, ipady=13, expand=0)
Button(frame1,text="Button 1") .pack(side=LEFT, padx=13, pady=13)
Button(frame1, text="Button 2") .pack(side=LEFT, padx=13, pady=13)
Button(frame1, text="Button 3") .pack (side=LEFT, padx=13, pady=13)
# The second window 
frame2 = Frame (win, relief=RAISED, borderwidth=1)
frame2 . pack (side=BOTTOM, fill=NONE, ipadx="1c", ipady="1c", expand=1)
Button (frame2, text="Button 4") .pack (side=RIGHT, padx="1c", pady="1c")
Button (frame2,text="Button 5") .pack (side=RIGHT, padx="1c", pady="1c")
Button (frame2,text="Button 6") .pack (side=RIGHT, padx="1c", pady="1c")
# The third window 
frame3 = Frame (win, relief=RAISED, borderwidth=2)
frame3. pack (side=LEFT, fill=X, ipadx="0.1i", ipady="0.1i", expand=1)
Button (frame3, text="Button 7") .pack(side=TOP, padx="0.1i", pady="0.1i")
Button (frame3, text="Button 8") .pack(side=TOP, padx="0.1i", pady="0.1i")
Button(frame3, text="Button 9") .pack(side=TOP, padx="0.1i", pady="0.1i")
# The fourth window 
frame4 = Frame (win, relief=RAISED, borderwidth=3)
frame4. pack (side=RIGHT, fill=Y, ipadx="13p", ipady="13p", expand=1)
Button(frame4, text="Button 13") . pack (side=BOTTOM, padx="13p",
pady="13p")
Button (frame4, text="Button 11") .pack (side=BOTTOM, padx="13p" ,
pady="13p")
Button (frame4, text="Button 12") .pack (side=BOTTOM, padx="13p",
pady="13p")
# Start the window's event loop 
win . mainloop()


grid

attribute Attribute analysis example
row and column It represents the grid in which row or column a control should be placed , All subscripts are from 0 The beginning of the plan xxx.grid(column=1,row=1)
rowspan and columnspan It means that a control will span several rows vertically or several columns horizontally , The default is 1 xxx.grid(column=1,row=1,columnspan=2)xxx.grid(column=1,row=1,rowspan=2)
padx and pady It represents the outer margin of a control , The distance between the edge of the control and the container where the control is located , Unit is pixel xxx.grid(column=1,row=1,padx=10)xxx.grid(column=1,row=1,pady=10)
ipadx and ipady It represents the inner margin of a control , The edge of the control and the content of the control ( Words, pictures, etc ) The distance between , Unit is pixel xxx.grid(column=1,row=1,ipadx=10)xxx.grid(column=1,row=1,ipady=10)
sticky It represents how a control is placed in the grid , Is it left or right , Up or down , Even if the window is enlarged, it will be aligned in the specified direction if sticky=N, Express North, As far north as possible / It's up there .
if sticky=S, Express South, As far south as possible / Stop below . if sticky=W, Express West, As far west as possible / Stop on the left . if sticky=E, Express East, As far east as possible / Stop on the right . if sticky=NS, Express NorthSouth, As far north and South as possible / Stretch up and down . if sticky=EW, Express EastWest, As far east and West as possible / Stretch left and right . if sticky=CENTER, Stop in the center as much as you can .


from tkinter import *
# main window 
win = Tk()
# Create a form 
frame = Frame (win, relief=RAISED, borderwidth=2)
frame.pack (side=TOP, fill=BOTH, ipadx=5, ipady=5, expand=1)
# Create an array of buttons 
for i in range (5):
for j in range (5):
Button (frame, text=" (" + str(i) + ","+ str(j)+ ")") .grid(row=i,column=j )
# Start the window's event loop 
win. mainloop()


Main window layout

from tkinter import *
# main window 
win = Tk()
win.title(' WeChat :civilpy')
winWidth = 700
winHeight = 350
# Get screen resolution ( Pixels )
screenWidth = win.winfo_screenwidth()
screenHeight = win.winfo_screenheight()
x = int((screenWidth - winWidth) / 2)
y = int((screenHeight - winHeight) / 2)
# Set the initial position of the window in the center of the screen 
win.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
# Set window icons 
win.iconbitmap("./images/favicon.ico")
# Set the window width and height fixed 
win.resizable(0, 0) # Prevent users from resizing 


Other controls

1、title: Set the title of the window

attribute Attribute analysis example
title Set the window title title(‘xxxxx’)
geometry Set window size , The middle can't be *, It is x geometry('200x100')
resizable Set whether the window can change height (height)、 wide (width),True To be able to change ,False For unchangeable resizable(width=False, height=True)

2、Label: label

attribute Attribute analysis example
text What needs to be displayed on the interface Label Label content Label(root,text=‘xxxxx’)
height Height of components ( Number of rows taken up ) Label(root,text=‘xxxxx’,height=2)
width Width of components ( Number of characters ) Label(root,text=‘xxxxx’,height=2,width=20)
fg Foreground font color Label(root,text=‘xxxxx’,fg='blue')--- The font is blue
bg The background color Label(root,text=‘xxxxx’,bg=‘red’)--- The display background is red
justify Alignment of multiline text , The optional parameter is : LEFT、 CENTER、RIGHT, They are left 、 In the middle 、 Align right Label(root,text=‘xxxxx’,justify=tk.LEFT)
padx The number of spaces on the left and right sides of the text ( The default is 1) Label(root,text=‘xxxxx’,padx=5)
pady The number of spaces on both sides of the text ( The default is 1) Label(root,text=‘xxxxx’,pady=5)
font Set font format and size Label(root,text=‘xxxxx’,font=(" Microsoft YaHei ", 12))
photo Set the background image , You need to specify the image path in advance photo=tk.PhotoImage(file=' Specify the image path ')Label(root,text=‘xxxxx’,image=photo)
compound Image background image position , The optional parameter is :botton、top、right、left、center( Next 、 On 、 Right 、 Left 、 Text over image ) photo=tk.PhotoImage(file=' Specify the image path ')Label(root,text=‘xxxxx’,image=photo,compound=center)


3、Button: Button

attribute Attribute analysis example
text The button icon shows the content Button(root,text='xxxx')
height Height of components ( Number of rows taken up ) Button(root,text='xxxx',height=2)
width Width of components ( Number of characters ) Button(root,text='xxxx',width=20)
fg Foreground font color Button(text='xxxx',fg='blue')--- The font color of the display button is blue
bg The background color Button(root,text='xxxx',bg='red')--- The display button has a red background
activebackground The background color when the button is pressed Button(root,text='xxxx',activebackground='grey')
activeforeground The foreground font color when the button is pressed Button(root,text='xxxx',activeforeground='white')
justify Alignment of multiline text , The optional parameter is : LEFT、 CENTER、RIGHT, They are left 、 In the middle 、 Align right Button(root,text=‘xxxxx’,justify=tk.LEFT)
padx The number of spaces on the left and right sides of the text ( The default is 1) Button(root,text='xxxx',padx=10)
pady The number of spaces on both sides of the text ( The default is 1) Button(root,text='xxxx',pady=10)
command Button triggers the execution of the command ( function ) Button(root,text='xxxx',command= function )


4、Entry: Input box

attribute Attribute analysis example
width Width of components ( Number of characters ) Entry(root,width=20)
fg Foreground font color Entry(root,fg='blue')
bg The background color Entry(root,bg='blue')
show take Entry Replace the text in the box with the specified character , Used to enter passwords, etc , Such as setting show="*" Entry(root,show="*")
state Set component status , The default is normal, Can be set to :disabled— Disable components ,readonly— read-only Entry(root,state=readonly)
textvariable Specify variables , You need to define a variable in advance , stay Entry Bind to get the value of the variable text=tk.StringVar()
Entry(root,textvariable=text)


5、Radiobutton: Radio buttons

attribute Attribute analysis example
text The radio box text shows the content Radiobutton(root,text='xxxx')
variable Radio index variables , Determine which radio box is selected by the value of the variable . A set of radio boxes uses the same index variable , You need to set a variable in advance color=tk.StringVar()
Radiobutton(root,variable=color)
value Set the value of the variable when the radio box is selected color=tk.StringVar()
Radiobutton(root,variable=color,value='red')
command The command to execute when the radio box is selected ( function ) color=tk.StringVar()
Radiobutton(root,variable=color,value='red',command= function )


6、Checkbuttion: Check box

attribute Attribute analysis example
text The text displayed in the check box Checkbutton(root,text='xxxx')
variable Check box index variable , Determine which check boxes are selected by the value of the variable . Each check box uses a different variable , Make the check boxes independent of each other , You need to define different variables in advance typeBlod=tk.IntVar()
Checkbutton(root,variable=typeBlod)
onvalue Check box selected ( It works ) Value of time variable , Different effects of branches can be judged by calculating values , The calculated value is set by yourself typeBlod=tk.IntVar()
Checkbutton(root,variable=typeBlod,onvalue=1)
offvalue Check box not selected ( Invalid ) Value of time variable , Different effects of branches can be judged by calculating values , Generally set as 0 typeBlod=tk.IntVar()
Checkbutton(root,variable=typeBlod,onvalue=1,offvalue=0)
command Command to execute when check box is selected ( function ) typeBlod=tk.IntVar()
Checkbutton(root,variable=typeBlod,onvalue=1,offvalue=0,command= function )


7、Text: The text box

attribute Attribute analysis example remarks
t.insert(mark, Content ) Insert text message ,mark It can be a line number , Or special signs t=tk.Text()
t.insert(END,' Inserted text message ')
INSERT: The insertion point of the cursor
CURRENT: The character position corresponding to the current position of the mouse END: This Textbuffer Last character of SEL_FIRST: Select the first character of the text field , If no region is selected, an exception is thrown SEL_LAST: Select the last character in the text field , If no region is selected, an exception is thrown
t.delete(mark1, mark2) Delete text messages INSERT: The insertion point of the cursor CURRENT: The character position corresponding to the current position of the mouse
END: This Textbuffer Last character of SEL_FIRST: Select the first character of the text field , If no region is selected, an exception is thrown SEL_LAST: Select the last character in the text field , If no region is selected, an exception is thrown


8、messagebox

The message pop-up box is used for info、warning、error Prompt box pop-up uses , We can use it according to our own needs

attribute Attribute profile example
showinfo info message , Pop up the prompt box msgbox.showinfo("INFO","Showinfo test"),INFO It's a reminder box title,Showinfo test It's the content of the prompt box
showwarning warning Warning message , Pop up warning box msgbox.showwarning("WARNING","Warning test"),WARNING It's a warning box title,Warning test It's the warning box
showerror error Error message prompt , The error box pops up msgbox.showerror("ERROR","Error test"),ERROR It's the error box title,Error test It's the contents of the error box
askquestion The question window prompts msgbox.askquestion("Question","Askquestion test")
askokcancel Confirm and cancel window prompt msgbox.askokcancel("OkCancel","Askokcancel test")
askyesno Confirm and cancel window prompt msgbox.askretrycancel("Retry","Askretrycancel test")
askretrycancel Retrying and canceling window prompts msgbox.askretrycancel("Retry","Askretrycancel test")

Conclusion

In the process of completing a product , There are also many details of the design , It's not going to unfold here , If you are interested, you can have a look at my finished products , It includes me 2020 Years of skill trees , It may inspire some of your Idea:

The owner 2020 Year of 3 A link to download packaged works :

https://pan.baidu.com/s/1kj29pFjLniQ9THbUSZMNlA

Extraction code : 6pp2


Reference for this issue :

https://so.csdn.net/so/search/blog?q=Tkinter&t=blog&p=1&s=0&tm=0&lv=-1&ft=0&l=&u=qq_41556318so.csdn.net

版权声明
本文为[osc_ beahvznj]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210115120225736z.html

  1. 小白量化投资交易入门课(python入门金融分析)
  2. Python:PyCharm选择性忽略PEP8警告
  3. Python: pychar selectively ignores pep8 warnings
  4. Django-模板
  5. Django template
  6. Python正则表达式大全
  7. 最全Python正则表达式来袭
  8. A python knowledge for Xiaobai
  9. 2. Flexible pandas index
  10. 1. Get to know pandas
  11. See how I use Python to create a magic with baby (one play can play for a day)?
  12. Wow, python can do real-time translation
  13. Python经典编程习题100例
  14. 100 examples of Python classic programming exercises
  15. Invincible, with Python for English teachers to develop a magic tool for English composition correction (support primary school to IELTS)
  16. 抖音数据采集教程,最全python库selenium自动化使用
  17. Pandas 11-综合练习
  18. Pandas 11 - comprehensive exercises
  19. Pandas基础|用户游览日志时间合并排序
  20. python自学 第三章 python语言基础之保留字、标识符与内置函数
  21. python学习例程3-函数
  22. Python GUI 之Tkinter小结 - 知乎
  23. Pandas foundation | user travel log time merge sort
  24. Chapter 3 reserved words, identifiers and built-in functions of the foundation of Python
  25. 【Python常用包】itertools
  26. Itertools
  27. [Python] Matplotlib 图表的绘制和美化技巧
  28. Drawing and beautifying skills of [Python] Matplotlib chart
  29. Drawing and beautifying skills of [Python] Matplotlib chart
  30. Python序列之列表(一)
  31. Python解析库lxml与xpath用法总结
  32. Python解析库lxml与xpath用法总结
  33. Usage Summary of Python parsing library lxml and XPath
  34. Usage Summary of Python parsing library lxml and XPath
  35. Python web/HTML GUI
  36. Why is sanic better than Django flame?
  37. Wechat applet Python sends subscription message
  38. Invincible, with Python for English teachers to develop an English composition correction artifact (support primary school to IELTS)
  39. How can I use Python to create a magic with children (one can play for one day)?
  40. Pandas module
  41. Machine learning in Python - Boston house price forecast
  42. 50 Great Python modules
  43. Share the survival status of Python practitioners and tell you the real salary of general programmers
  44. Pandas basic operation update
  45. Python Programming day02 Python operator
  46. Usage Summary of Python parsing library lxml and XPath
  47. 1. First meeting pandas
  48. Conversion between Python and base conversion between Python and base
  49. Basics of Python
  50. Fundamentals of python (XIV): errors and exceptions
  51. Fundamentals of python (8): time related modules
  52. Fundamentals of python (I): necessary knowledge for getting started
  53. Operators in Python 3
  54. The list of national computer non graduate schools (captured by Python), just look at this one!
  55. Python data visualization: Seaborn
  56. Quick start pandas (lower)
  57. Operators in Python 3
  58. Python tarfile module
  59. Python basic syntax