如何控制 Tkinter 中視窗的自動調整大小?


透過定義 geometry(“width × height”)方法,可以手動調整 Tkinter 視窗大小。我們可以透過將空值傳遞給幾何管理器來使視窗自動調整大小或重置為其原始大小。一旦空值傳遞給該方法,它將自動調整大小。在這個示例中,我們將建立一個 Tkinter 應用程式,它將顯示一個具有定義大小的頂級視窗(彈出視窗)。當我們按 RESET 按鈕時,它將再次調整為預設大小。

示例

#Import the library
from tkinter import *
from tkinter import ttk

#Create an instance of tkinter frame
win= Tk()

#Set the window geometry
win.geometry("750x200")

#Create a Label
Label(win, text= "Tkinter is a GUI Library in Python", font=('Helvetica 15 bold')).pack(pady=20)

#Define a function to reset the window size
def reset_win():
   win.wm_geometry("750x250")
   button.destroy()

#Create a Button to Hide/ Reveal the Main Window
button= ttk.Button(win, text="RESET" ,command= reset_win)
button.pack(pady=50)

win.mainloop()

輸出

執行以上程式碼將顯示一個包含一個按鈕的視窗。一旦我們點選 RESET 按鈕,它將調整為預設大小,防止視窗手動調整大小。

現在,單擊 Button 重置主視窗的大小,它將自動調整為其預設大小。

更新於:2021 年 5 月 4 日

4K+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告