如何從 Tkinter 文字小元件中清除所有內容?
Tkinter 文字小元件不僅僅是多行 Entry 小元件。它支援實現多種顏色文字、超連結文字等。
我們假設在應用程式中建立了文字小元件。現在,要清除文字小元件,我們可以使用 delete("1.0", END) 方法。它可以在回撥函式或透過 Button 類物件觸發的事件中呼叫。
示例
# Import the required libraries from tkinter import * # Create an instance of Tkinter Frame win = Tk() # Set the geometry win.geometry("750x250") # Define a function to clear the text widget def clear(): text.delete('1.0', END) # Create a Text Widget text = Text(win, width=50, height=10) text.insert("1.0", "This is my Text Widget") text.pack(padx=5, pady=5) # Create a Button to delete all the text Button(win, text="Clear All", command=clear, font="aerial 12 bold").pack(padx=5, pady=5) win.mainloop()
輸出
執行以上程式碼將顯示一個文字小元件和一個用於清除文字小元件的按鈕。
現在,點選“全部清除”按鈕以清除文字小元件內的文字。
廣告