如何在 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.