如何刪除 Tkinter 文字部件中的全部內容?


Tkinter 文字部件接受並支援多行使用者輸入。我們可以指定文字部件的其他屬性,例如寬度、高度、背景、邊框寬度以及其他屬性。

假設我們想刪除給定文字部件中的所有內容,那麼我們可以使用delete("1.0", END) 函式。

示例

在此示例中,我們將使用 Python 中的random 模組插入一些隨機文字,並使用 delete() 方法擦除。

#Import the required Libraries
from tkinter import *
from tkinter import ttk
import random

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

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

#Define functions to insert/erase the text
def insert_text():
   text.insert(INSERT,chr(random.randint(ord('a'),ord('z'))))

def erase_text():
   text.delete("1.0",END)

#Create a Text widget
text= Text(win, width=50, height= 5)
text.focus_set()
text.pack()

#Add a bottom widgets
button1= ttk.Button(win, text= "Insert",command= insert_text)
button1.pack(side=TOP)
button2= ttk.Button(win, text= "Erase",command= erase_text)
button2.pack(side=TOP)
#Create a Button widget
win.mainloop()

輸出

執行以上程式碼,將顯示一個包含文字部件和用於刪除其全部內容的按鈕的視窗。

現在,單擊“插入”按鈕以在文字框中插入一些隨機字元。一旦在文字框中插入字元,我們可以透過單擊“刪除”按鈕來刪除所有內容。

更新於: 04-May-2021

297 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
Advertisement