如何在 Tkinter 中找出画布项的大小?


如要查找画布项的最小高度和宽度,我们可以使用 Canvas 的边框属性。基本上,边框属性使画布项能够返回画布内的位置。在 bbox(item) 方法中,每个项最初定义了该项的最小和最大宽度和高度。

示例

#Import required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Initialize a Canvas
canvas= Canvas(win, width= 600, height= 200)
#Add a text inside the Canvas
text= canvas.create_text(300,20, text= "This is a New Line Text", font=16,anchor= "n")
canvas.pack()
#Finding the width and height of canvas Items
bounds= canvas.bbox(text)
width= bounds[3]-bounds[0]
height= bounds[3]- bounds[1]
print(width)
print(height)

win.mainloop()

输出

运行以上代码,会显示出一个包含画布项(文本)的窗口。它会在终端中打印该项的大小。

画布项的大小为:

-154
23

更新时间:2021 年 5 月 3 日

2K+ 浏览次数

开启你的 职业生涯

完成课程认证

开始学习
广告
© . All rights reserved.