如何在 Tkinter 中點選按鈕後清除 Entry 元件的內容?
Tkinter Entry 元件用於顯示單行文字,通常作為使用者輸入。我們可以透過定義一個方法 **delete(0, END)** 來清除 Entry 元件的內容,該方法旨在清除指定範圍內的所有內容。可以透過定義一個函式來呼叫此方法,該函式可用於 建立按鈕物件。
示例
在這個例子中,我們建立了一個 Entry 元件和一個按鈕,用於清除元件中的所有內容。
#Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("650x250") #Define a function to clear the Entry Widget Content def clear_text(): text.delete(0, END) #Create a entry widget text= Entry(win, width=40) text.pack() #Create a button to clear the Entry Widget Button(win,text="Clear", command=clear_text, font=('Helvetica bold',10)).pack(pady=5) win.mainloop()
輸出
執行以上程式碼將顯示一個視窗,其中包含一個 Entry 元件和一個按鈕,可用於清除 Entry 欄位中寫入的文字。
現在點選“清除”按鈕來清除 Entry 元件。
廣告