当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Tkinter grid()用法及代码示例


网格几何管理器将小部件放置在二维表中。主窗口小部件分为许多行和列,结果表中的每个“cell”可以容纳一个窗口小部件。网格管理器是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()。



相关用法


注:本文由纯净天空筛选整理自sanjeev2552大神的英文原创作品 Python | grid() method in Tkinter。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。