The grid() function in Tkinter is used to create a grid layout manager. It organizes widgets in a table-like structure with rows and columns.

Syntax:

widget.grid(options)

Options:

  • 'row': Specifies the row index of the widget (starts from 0).
  • 'column': Specifies the column index of the widget (starts from 0).
  • 'sticky': Defines how the widget should align within its cell. It can have values like 'n', 's', 'w', 'e', 'nw', 'ne', 'sw', 'se', 'center'.
  • 'padx': Specifies the padding in the x-direction.
  • 'pady': Specifies the padding in the y-direction.

Example:

from tkinter import *

root = Tk()

# Creating labels and placing them in a grid layout
label1 = Label(root, text='Label 1')
label1.grid(row=0, column=0)

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

label3 = Label(root, text='Label 3')
label3.grid(row=1, column=0, columnspan=2, sticky='w')

root.mainloop()

In the above example, three labels are created and placed in a grid layout using the grid() function. label1 is placed in the first row and first column, label2 is placed in the first row and second column, and label3 is placed in the second row, spanning two columns, and aligned to the west ('w').

Tkinter grid() Function: Create Grid Layouts in Python

原文地址: https://www.cveoy.top/t/topic/lMGK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录