Introduction to GUI Interface Layout of Tkinter

Introduction to GUI Interface Layout of Tkinter

For the basics of Python’s Tkinter window, please refer to https://blog.csdn.net/cnds123/article/details/127227651

Tkinter itself does not provide a way to drag and drop controls to create a GUI interface, but provides three geometry manager methods: pack, grid and place, each of which has its own advantages and applicable scenarios. Choose the most suitable layout method.

Tkinter geometry manager (geometry manager), also called layout (layout), is used to control the typesetting and layout of widgets (Widgets) in the form.

A widget (Widget) is also known as a component (component) or a control (control), these terms are used interchangeably, and is called a Widget in the official Tkinter documentation. They both refer to visual elements in the user interface. In Tkinter, some common widgets are as follows:

Label: Used to display text or images.

Button (button): used to trigger a response event or perform an action.

Entry (input box): Used to receive a single line of text input from the user.

Text (text box): used to receive and display multi-line text input.

Checkbutton (check box): used to select one or more options.

Radiobutton (radio button): Used to select one from multiple options.

Listbox (list box): used to display a list or select list items.

Combobox (combo box): Combines the functions of a text box and a drop-down list.

Frame (frame): used to create a container that can contain other Widgets.

Canvas: Used to draw graphics, images, and custom interface elements.

Scrollbar: Used to implement scrolling on large content areas.

etc.

The general syntax format of various widgets (Widget) in Tkinter is as follows:

widget = WidgetClass(parent, options)

Among them, WidgetClass is the control class name, parent is the parent window object, options is the options and properties of the control, which can be one or more parameters. Here are some commonly used selectors and attributes:

text: Display text of the control.

width and height: Width and height of the control in pixels.

bg and fg: the background color and foreground color of the control.

font: The font setting of the control.

command: The function executed after the button control is clicked.

variable: The state variables of controls such as multi-select boxes and radio boxes.

value: The value of the control.

image: The image object of the image control.

The above are some commonly used control options and properties, and different controls have other different selectors and properties.

For example:

Label: label = Label(root, text="Hello, World!")

Button: button = Button(root, text="Click me!", command=callback)

Entry: entry = Entry(root, width=10)

Text: text = Text(root, height=5, width=30)

Canvas: canvas = Canvas(root, width=300, height=200)

Listbox: listbox = Listbox(root)

Checkbutton: checkbutton = Checkbutton(root, text="Check me!")

Radiobutton: radiobutton = Radiobutton(root, text="Option 1", value=1)

Scale: scale = Scale(root, from_=0, to=100, orient=HORIZONTAL)

Where root is the main window object, and these syntax formats are also called constructors (Constructor), which are used to create instances of various widgets (Widget). Every widget (Widget) must have a parent container (parent), which is the main window or child window to which the control belongs. When creating a widget (Widget), you need to pass its parent window object as the first parameter to the constructor.

Using widgets (Widget) in tkinter usually requires the following steps:

1. Import the tkinter library.

2. Create a Root Window object: Next, you can create a Root Window object, which is the top-level window of your tkinter program. Create a root window with the following line of code:

root = tk.Tk()

The root window is the main window for the entire tkinter program.

3. Create a widget (Widget) object: Before creating a widget object, you need to know the type and properties of each widget. Choose the appropriate widget for your needs.

For example, to create a label widget, the following line of code can be used:

label = tk.Label(root, text="Hello, world!")

The preceding code creates a label widget called label and places it in the root window. text is the text of the label.

4. Layout widget (Widget): Once the widget is created, you can use the layout manager to position and size the widget within the root window. Commonly used layout managers are pack(), grid(), and place().

5. Register event handlers, such as button click events, etc.

6. Enter the main message loop (Main Event Loop): Finally, you need to enter the main message loop to respond to user operations and events. Enter the main message loop with:

root.mainloop()

It should be noted that there may be different properties and methods in different controls, so the specific usage syntax needs to be adjusted according to different controls. In addition, you can also dynamically modify the property value of the control through the config() method or directly access the property.

pack layout

pack() is a relatively simple layout method. Without any parameters, it will arrange the controls in the order they were added, from top to bottom, line by line, and display them in the center by default. The basic syntax of the pack method is as follows:

widget.pack(options)

Among them, widget represents the widget to be placed; options is an optional parameter list, as follows:

parameter

illustrate

anchor

The alignment of the component in the window, there are 9 orientation parameter values, such as "n"/"w"/"s"/"e"/"ne", and "center" etc. )

expand

Whether the window can be expanded, the parameter value is True (extended) or False (not expanded), the default is False, if set to True, the position of the control is always at the center of the window

fill

The parameter value is X/Y/BOTH/NONE, which means that the control is allowed to be stretched in both directions horizontally/vertically/simultaneously. For example, when fill = X, the control will occupy all the remaining space in the horizontal direction.

ipadx, ipads

It needs to be used together with the fill parameter value, indicating the distance (inner margin) between the component and the content and the component border, such as the distance between the text content and the component border, in pixels (p), or centimeters (c), inches (i)

padx,pady

Used to control the top, bottom, left and right distances (margins) between components, in pixels (p), or centimeters (c), inches (i)

side

Where the component is placed in the window, the parameter values ​​are 'top', 'bottom', 'left', 'right'. Note that you need to use the string format when the word is lowercase, and you don't need to use the string format if it is an uppercase word

The sample code for the usage of the pack layout method is as follows:

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="Button 1")
button1.pack(side="left")

button2 = tk.Button(root, text="Button 2")
button2.pack(side="left")

button3 = tk.Button(root, text="Button 3")
button3.pack(side="right")

root.mainloop()

grid layout

Grid is a grid layout, which is equivalent to treating the window as a table composed of rows and columns, and each cell in the table can place a control. The basic syntax of the grid method is as follows:

widget.grid(options)

Among them, widget represents the widget to be placed; options is an optional parameter list, as follows:

parameter

illustrate

column

The column where the control is located in the table, the leftmost column of the form is the starting column, and the default is column 0

columnsapn

The number of columns spanned by the control instance, the default is 1 column, and multiple adjacent cells in a row can be merged through this parameter.

ipadx, ipads

It is used to control the padding, filling the space of the specified size in the left, right, up and down directions inside the cell.

padx,pady

It is used to control the outer margin, and fill the space of the specified size in the left, right, up and down directions outside the cell.

row

The row where the control is located in the table, the top of the form is the starting row, and the default is row 0

rowspan

The number of rows spanned by the control instance, the default is 1 row, and multiple adjacent cells in a column can be merged through this parameter.

sticky

This property is used to set the position of the control in the cell, the parameter value is the same as the anchor, if this parameter is not set, the control is centered in the cell

The grid layout method usage sample code is as follows:

import tkinter as tk

root = tk.Tk()

label1 = tk.Label(root, text="Label 1")
label1.grid(row=0, column=0)

label2 = tk.Label(root, text="Label 2")
label2.grid(row=0, column=1)

label3 = tk.Label(root, text="Label 3")
label3.grid(row=1, column=0, columnspan=2)

root.mainloop()

place layout

Compared with the first two layout methods, using the place() method for layout management is more refined. Through the place() layout manager, you can directly specify the absolute position of the control in the form, or the relative position relative to other controls. .

The basic syntax of the place method is as follows:

widget.place(options)

Among them, widget represents the widget to be placed; options is an optional parameter list, as follows:

parameter

illustrate

anchor

Define the orientation of the control in the form, the parameter value is N/NE/E/SE/S/SW/W/NW or CENTER, the default value is NW

bordermode

Define whether the coordinates of the control should consider the width of the boundary, the parameter value is OUTSIDE (excluding the boundary) or INSIDE (including the boundary), and the default value is INSIDE.

x、y

Defines the starting absolute position of the control in the root form in the horizontal and vertical directions

relx、rely

1. Define the relative position of the control relative to the root window (or other controls) in the horizontal and vertical directions (that is, the displacement ratio), and the value range is between 0.0 and 1.0. 2. You can set the in_ parameter item, relative to some
other position of controls

height、width

The height and width of the control itself (in pixels)

relheight、relwidth

The ratio of the height and width of the control to the height and width of the root form, and the value is also between 0.0 and 1.0

The sample code for the usage of the place layout method is as follows:

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="Button 1")
button1.place(x=10, y=10, width=100, height=50)

button2 = tk.Button(root, text="Button 2")
button2.place(x=120, y=10, width=100, height=50)

button3 = tk.Button(root, text="Button 3")
button3.place(x=10, y=70, width=210, height=50)

root.mainloop()

Tkinter provides these three layout managers, each of which has its applicable scenarios and characteristics. Mixing pack, grid, and place layout managers is generally not recommended. But in some special cases, it is also possible to use different layout managers in different widgets. For example, use the pack layout manager to create two frames (Frame), and then use the grid or place layout manager in the frame to further layout components. This approach can combine different layout requirements to a certain extent, but it still needs to be handled carefully to avoid confusing layout results.

[In Tkinter, there are several types of containers that can be used to organize and accommodate other Widgets. In addition to Frame, Toplevel, LabelFrame, etc. can also be used as containers. A container is a special kind of Widget, which is special in that it has the ability to accommodate other components, and plays an organizational and management role in interface design.

The following is the implementation code for the login interface with three layouts

1. In the case of using pack layout , first look at the effect

The source code is as follows. In the above code, we created three Frame containers, which are used to place the controls of each row:

#pack布局
from tkinter import *

# 创建一个窗体,名称为root
root = Tk()
# 为窗体添加标题
root.title("用户登录")
root.geometry("400x180")

root.resizable(width=False, height=False) # 不可调整大小

frame1 = Frame(root)
frame1.pack(side=TOP, pady=5)
Label_username = Label(frame1,text = "登录名:",font = ("华为黑体",16)).pack(side = LEFT, padx=5)
Entry_username = Entry(frame1,font = ("华文黑体",16),width = 20).pack(side = LEFT, padx=5)

frame2 = Frame(root)
frame2.pack(side=TOP, pady=5)
Label_password = Label(frame2,text = "密  码:",font = ("华为黑体",16)).pack(side = LEFT, padx=5)
Entry_password = Entry(frame2,font = ("华文黑体",16),width = 20, show="*").pack(side = LEFT, padx=5) #使用show属性将密码显示为星号

frame3 = Frame(root)
frame3.pack(side=TOP, pady=5)
Button_login = Button(frame3,text = "登录",font = ("华文黑体",16),width = 8).pack(side = LEFT, padx=5)
Button_cancer = Button(frame3,text = "取消",font = ("华文黑体",16),width = 8).pack(side = LEFT, padx=5)

root.mainloop()

2. In the case of grid layout , first look at the effect

[Hint, the orange line in the above picture is added by me to enhance understanding, and the actual operation effect is not]

The source code is as follows:

# grid布局
from tkinter import *

root = Tk()
root.title("用户登录")
root.geometry("400x180")

root.resizable(width=False, height=False) # 不可调整大小

# 占位
label = Label(root,text = "     ").grid(row = 0,column = 0,rowspan = 2)

Label_username = Label(root,text = "用户名:",font = ("华文黑体",16)).grid(row = 0,column = 1)
Entry_username = Entry(root,font = ("华文黑体",16)).grid(row =0,column = 2)
Label_password = Label(root,text = "密  码:",font = ("华文黑体",16)).grid(row = 1,column = 1)
Entry_password = Entry(root,font = ("华文黑体",16), show="*").grid(row =1,column = 2)  #使用show属性将密码显示为星号
Button_login = Button(root,text = "登录",width = 8,font = ("华文黑体",16)).grid(row = 3,column = 2,sticky = "e")
Button_cancer = Button(root,text = "取消",width = 8,font = ("华文黑体",16)).grid(row =3,column = 2,sticky = "w")

root.mainloop()

3. In the case of using place layout , first look at the effect

The source code is as follows:

# place布局
from tkinter import *

root = Tk()
root.title("用户登录")
root.geometry("400x180")

root.resizable(width=False, height=False) # 不可调整大小

Label_username = Label(root,text = "登录名:",font = ("华为黑体",16)).place(x = 40,y = 20)
Entry_username = Entry(root,font = ("华文黑体",16),width = 20).place(x = 120,y = 20)
Label_password = Label(root,text = "密  码:",font = ("华为黑体",16)).place(x = 40,y = 60)
Entry_password = Entry(root,font = ("华文黑体",16),width = 20, show="*").place(x = 120,y = 60) #使用show属性将密码显示为星号
Button_login = Button(root,text = "登录",font = ("华文黑体",16),width = 8).place(x = 70,y = 120)
Button_cancer = Button(root,text = "取消",font = ("华文黑体",16),width = 8).place(x = 210,y = 120)

root.mainloop()

Some additional notes on the above code

1. Add a show="*" parameter to the constructor of the Entry control, and replace the entered text with asterisks. In this way, the password entered by the user will not be displayed in plain text.

2. You can use the minsize() method and maxsize() method to set the minimum size and maximum size of the window respectively. like:

root.minsize(400, 180) # set the minimum size

root.maxsize(600, 380) # set the maximum size

3. You can use the resizable() method to control whether the tkinter window can be resized. This method accepts two parameters (the first is the horizontal direction, the second is the vertical direction) to control the adjustable boundary conditions of the window, where each parameter can set a value:

True: Adjustable;

False: not adjustable;

The resizable() method is True by default for adjustments in all directions, that is, the window can be resized horizontally and vertically by default, which is equivalent to setting resizable(True, True). If you want to disable window resizing in any direction, you can set both parameters to False. If you only want to disable resizing in the horizontal or vertical direction, you can set the corresponding parameter to False.

If you want to disable resizing in all directions, you can set both parameters to False. like:

root.resizable(False, False) # not resizable or root.resizable(width=False, height=False)

Guess you like

Origin blog.csdn.net/cnds123/article/details/131341244