如何使 Tkinter 元件不可見?


若要使 tkinter 元件不可見,我們可以使用 pack_forget() 方法。它通常用於取消對映視窗中的元件。

示例

在下例中,我們將建立一個文字標籤和一個按鈕,該按鈕可用於觸發文字標籤元件上的不可見事件。

#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("600x250")

#Set the resizable property False
win.resizable(False, False)

#Make the widgets Invisible
def make_invisible(widget):
   widget.pack_forget()

#Create a label for the window or frame
label=Label(win, text="Hello World!", font=('Helvetica bold',20),
anchor="center")
label.pack(pady=20)

#Create a button to make the widgets invisible
btn=Button(win, text="Click", font= ('Helvetica bold', 10), command=lambda:
make_invisible(label))
btn.pack(pady=20)

win.mainloop()

輸出

執行以上程式碼會生成以下視窗 −

現在單擊“單擊”按鈕,使文字標籤不可見。

更新於: 26-3-2021

5K + 瀏覽量

開啟你的職業生涯

透過完成課程獲取認證

入門
廣告
© . All rights reserved.