如何在 Tkinter 中顯示和隱藏小元件?
Tkinter 是一個用於建立和開發基於 GUI 的應用程式的 Python 庫。假設我們必須建立一個應用程式,以便我們可以顯示或隱藏小元件。
- 要顯示小元件,請使用**pack()**幾何管理器
- 要從應用程式中隱藏任何小元件,請使用**pack_forget()**方法。
示例
讓我們透過下面的例子來理解如何顯示/隱藏小元件 −
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Define the style for combobox widget style = ttk.Style() style.theme_use('xpnative') # Define a function to show/hide widget def show_widget(): label.pack() def hide_widget(): label.pack_forget() b1.configure(text="Show", command=show_widget) # Add a label widget label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Aerial 11')) label.pack(pady=30) # Add a Button widget b1 = ttk.Button(win, text="Hide", command=hide_widget) b1.pack(pady=20) win.mainloop()
輸出
執行上述程式碼將開啟一個視窗,其中有一個按鈕用於顯示/隱藏應用程式中的小元件。
現在,單擊按鈕以顯示/隱藏視窗中的標籤文字。
廣告