如何獲取 Tkinter 視窗的寬度和高度?
Tkinter 最初會建立一個視窗例項,此視窗是包含所有小部件和元素的容器。如果要調整視窗大小,我們可使用 geometry 方法,透過定義高度和寬度值來調整。
為了獲取 tkinter 視窗的高度和寬度,我們可使用 winfo_width() 和 winfo_height() 助手方法,它們可以幫助獲得 tkinter 視窗的當前高度和寬度。
示例
# Import tkinter library from tkinter import * # Create an instance of tkinter frame win = Tk() # Set the Geometry win.geometry("750x250") def print_width(): print("The width of Tkinter window:", win.winfo_width()) print("The height of Tkinter window:", win.winfo_height()) # Create a Label Label(win, text="Click the below Button to Print the Height and width of the Screen", font=('Helvetica 10 bold')).pack(pady=20) # Create a Button for print function Button(win, text="Click", command=print_width).pack(pady=10) win.mainloop()
輸出
執行以上程式碼將顯示一個包含按鈕的視窗。
如果單擊這個按鈕,它將在控制檯上列印當前 tkinter 視窗的高度和寬度。
The width of Tkinter window: 750 The height of Tkinter window: 250
廣告