本文概述
- grid_location()方法–
- grid_size()方法–
grid_location()方法– 此方法返回一个包含(列, 行)任何指定小部件的元组。由于此方法是窗口小部件方法, 因此无法将其与主对象一起使用(或Tk()目的)。为了使用此方法, 你首先应创建一个帧并将其视为父母(或主人)。
语法:widget.grid_location(x, y)参数:x和y是相对于小部件(父小部件)左上角的位置。在下面的示例中, grid_location()用于获取小部件在帧小部件。
# This imports all functions in tkinter module
from tkinter import * from tkinter.ttk import *# creating master window
master = Tk()# This method is used to get the position
# of the desired widget available in any
# othet widget
def click(event):# Here retrieving the size of the parent
# widget relative to master widget
x = event.x_root - f.winfo_rootx()
y = event.y_root - f.winfo_rooty()# Here grid_location() method is used to
# retrieve the relative position on the
# parent widget
z = f.grid_location(x, y)# printing position
print (z)# Frame widget, wil work as
# parent for buttons widget
f = Frame(master)
f.pack()# Button widgets
b = Button(f, text = "Button" )
b.grid(row = 2 , column = 3 )c = Button(f, text = "Button2" )
c.grid(row = 1 , column = 0 )# Here binding click method with mouse
master.bind( "<
Button-1>
" , click)# infinite loop
mainloop()
grid_size()方法– 此方法用于获取任何父窗口小部件中存在的网格总数。这是一种窗口小部件方法, 因此无法将其与主对象一起使用。一个必须创建一个帧小部件。
语法:(列, 行)= widget.grid_size()返回值:返回列和行(网格)的总数。以下是Python代码-
# This imports all functions in tkinter module
from tkinter import * from tkinter.ttk import *# creating master window
master = Tk()# This method is used to get the size
# of the desired widget i.e number of grids
# available in the widget
def grids(event):# Here, grid_size() method is used to get
# the total number grids available in frame
# widget
x = f.grid_size()# printing (columns, rows)
print (x)# Frame widget, will work as
# parent for buttons widget
f = Frame(master)
f.pack()# Button widgets
b = Button(f, text = "Button" )
b.grid(row = 1 , column = 2 )c = Button(f, text = "Button2" )
c.grid(row = 1 , column = 0 )# Here binding click method with mouse
master.bind( "<
Button-1>
" , grids)# infinite loop
mainloop()
输出如下:
每次单击鼠标按钮时, 它将返回相同的值, 直到未添加更多小部件或行数和列数未增加。
(3, 2)
【Python Tkinter grid_location()和grid_size()方法】首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
推荐阅读
- Python Tkinter frame小部件用法示例
- Python Tkinter–ListBox小部件
- Python Tkinter–菜单按钮小部件
- Python Tkinter–Message消息小部件用法
- Python Tkinter–MessageBox小部件用法示例
- Python Tkinter使用Canvas.move()方法移动对象
- Python Tkinter比例小部件
- Python Tkinter–ScrolledText小部件用法
- Python Tkinter–SpinBox用法示例