如何在 Tkinter 中單擊 Entry 元件本身時清除文字元件內容?


Tkinter 文字元件是一個輸入元件,支援多行使用者輸入。它也被稱為文字編輯器,允許使用者在其內部編寫內容和資料。可以使用delete(0,END)命令來清除文字元件的內容。同樣,我們還可以透過單擊 Entry 小元件本身來清除內容。 這可以透過將函式繫結到單擊事件來實現。

舉例

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x250")

#Define a function to clear the content of the text widget
def click(event):
   name.configure(state=NORMAL)
   name.delete(0, END)
   name.unbind('<Button-1>', clicked)

#Create a Label widget
label = Label(win, text= "Enter Your Name", font= ('Helvetica 13 bold'))
label.pack(pady= 10)

#Create an Entry widget
name = Entry(win, width=45)
name.insert(0, 'Enter Your Name Here...')
name.pack(pady=10)

#Bind the Entry widget with Mouse Button to clear the content
clicked = name.bind('<Button-1>', click)
win.mainloop()

輸出

執行上面的程式碼將顯示一個帶有 Entry 元件的視窗。

當我們單擊 Entry 欄位時,它會自動清除其內容。

更新於: 2021 年 5 月 26 日

4K+ 瀏覽

開啟你的 職業生涯

完成課程認證

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