如何清除 Tkinter 中的框架?


Tkinter 框架用於以美觀的方式對過多的控制元件進行分組和組織。框架元件可以包含按鈕控制元件、輸入控制元件、標籤、捲軸和其他控制元件。

如果我們想清空框架內容或刪除框架內的所有控制元件,可以使用 destroy() 方法。此方法可以透過使用 winfo_children() 定位框架的子項來呼叫。

示例

#Import the required libraries
from tkinter import *

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

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

#Create a frame
frame = Frame(win)
frame.pack(side="top", expand=True, fill="both")

#Create a text label
Label(frame,text="Enter the Password", font=('Helvetica',20)).pack(pady=20)

def clear_frame():
   for widgets in frame.winfo_children():
      widgets.destroy()

#Create a button to close the window
Button(frame, text="Clear", font=('Helvetica bold', 10), command=
clear_frame).pack(pady=20)

win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,其中包含一個按鈕“清除”,該按鈕針對框架內的所有控制元件並將其清除。

現在單擊“清除”按鈕,它將清除框架內的所有控制元件。

更新於:26-Mar-2021

23K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.