Grid几何图形管理器将小部件放在一个二维表中。主小部件被分成若干行和列,结果表中的每个“单元格”都可以包含一个小部件。
网格管理器是Tkinter中最灵活的几何管理器。如果你不想学习如何以及何时使用这三种管理方式,你至少应该学习这一种。
考虑以下示例–
使用包管理器是可能的, 但是它需要大量额外的框架小部件, 并且需要做很多工作才能使外观看起来更好。如果改为使用网格管理器, 则每个小部件只需要调用一次即可正确布置所有内容。
使用网格管理器很容易。只需创建小部件,并使用grid方法告诉管理器将它们放在哪一行和哪一列中。你不必预先指定网格的大小;管理器从其中的小部件自动确定。
代码1:
# import tkinter module
from tkinter import * from tkinter.ttk import *
# creating main tkinter window/toplevel
master = Tk()
# this wil create a label widget
l1 = Label(master, text = "First:" )
l2 = Label(master, text = "Second:" )
# grid method to arrange labels in respective
# rows and columns as specified
l1.grid(row = 0 , column = 0 , sticky = W, pady = 2 )
l2.grid(row = 1 , column = 0 , sticky = W, pady = 2 )
# entry widgets, used to take entry from user
e1 = Entry(master)
e2 = Entry(master)
# this will arrange entry widgets
e1.grid(row = 0 , column = 1 , pady = 2 )
e2.grid(row = 1 , column = 1 , pady = 2 )
# infinite loop which can be terminated by keyboard
# or mouse interrupt
mainloop()
输出如下:
代码2:
创建上面显示的布局。
# import tkinter module
from tkinter import * from tkinter.ttk import *
# creating main tkinter window/toplevel
master = Tk()
# this will create a label widget
l1 = Label(master, text = "Height" )
l2 = Label(master, text = "Width" )
# grid method to arrange labels in respective
# rows and columns as specified
l1.grid(row = 0 , column = 0 , sticky = W, pady = 2 )
l2.grid(row = 1 , column = 0 , sticky = W, pady = 2 )
# entry widgets, used to take entry from user
e1 = Entry(master)
e2 = Entry(master)
# this will arrange entry widgets
e1.grid(row = 0 , column = 1 , pady = 2 )
e2.grid(row = 1 , column = 1 , pady = 2 )
# checkbutton widget
c1 = Checkbutton(master, text = "Preserve" )
c1.grid(row = 2 , column = 0 , sticky = W, columnspan = 2 )
# adding image (remember image should be PNG and not JPG)
img = PhotoImage( file = r "C:\Users\Admin\Pictures\capture1.png" )
img1 = img.subsample( 2 , 2 )
# setting image with the help of label
Label(master, image = img1).grid(row = 0 , column = 2 , columnspan = 2 , rowspan = 2 , padx = 5 , pady = 5 )
# button widget
b1 = Button(master, text = "Zoom in" )
b2 = Button(master, text = "Zoom out" )
# arranging button widgets
b1.grid(row = 2 , column = 2 , sticky = E)
b2.grid(row = 2 , column = 3 , sticky = E)
# infinite loop which can be terminated
# by keyboard or mouse interrupt
mainloop()
输出如下:
警告:切勿混grid()和pack()在同一主窗口中。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
评论前必须登录!
注册