个性化阅读
专注于IT技术分析

Python Tkinter grid_location()和grid_size()方法

本文概述

Tkinter用于开发GUI(图形用户界面)应用程序。它支持各种小部件以及各种小部件方法或通用小部件方法。

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 DS课程。


赞(0)
未经允许不得转载:srcmini » Python Tkinter grid_location()和grid_size()方法

评论 抢沙发

评论前必须登录!