首先,让我们弄清楚术语:您不是在创建小部件,而是在创建画布项。 Tkinter 文本小部件和画布文本项之间存在很大差异。
有两种方法可以设置画布文本项的文本。可以使用itemconfigure设置text属性,也可以使用画布的insert方法在文本项中插入文本。
在以下示例中,文本项将显示字符串“this is the new text”:
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
canvas = tk.Canvas(self, width=800, height=500)
canvas.pack(side="top", fill="both", expand=True)
canvas_id = canvas.create_text(10, 10, anchor="nw")
canvas.itemconfig(canvas_id, text="this is the text")
canvas.insert(canvas_id, 12, "new ")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()