如何使用按钮设置 Tkinter 文本控件的文本
Jinku Hu
2024年2月15日

Tkinter 的 Text
文本控件没有专用的 set
方法来设置文本控件的内容。如果我们需要更改其内容,它首先需要删除现有内容,然后插入新内容。
使用 delete
和 insert
方法在文本
中设置文本的完整工作代码
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def setTextInput(text):
textExample.delete(1.0, "end")
textExample.insert(1.0, text)
textExample = tk.Text(root, height=10)
textExample.pack()
btnSet = tk.Button(
root, height=1, width=10, text="Set", command=lambda: setTextInput("new content")
)
btnSet.pack()
root.mainloop()
textExample.delete(1.0, "end")
正如如何清除 Tkinter Text
文本框一文中介绍的那样,Text
的 delete
方法会删除文本框中指定范围的字符。
Text
控件中的内容的第一个字符是 1.0
,end
是内容的最后一个字符。因此,它将删除文本框中的所有内容。
textExample.insert(1.0, text)
insert
方法将文本插入指定位置。在上面的代码中,它在开头插入了 text
。
作者: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn