问题
I have a Tkinter canvas populated with text and canvas windows, or widgets, created using the create_text
and create_window
methods. The widgets I place on the canvas are text widgets, and I want to insert text into them after they are created and placed. I can't figure out how to do this, if it's even possible. I realise you can edit them after creation using canvas.itemconfig(tagOrId, cnf)
, but text can't be inserted that way. Is there a solution to this?
回答1:
First, lets get the terminology straight: you aren't creating widgets, you're creating canvas items. There's a big difference between a Tkinter text widget and a canvas text item.
There are two ways to set the text of a canvas text item. You can use itemconfigure to set the text
attribute, and you can use the insert method of the canvas to insert text in the text item.
In the following example, the text item will show the string "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()
来源:https://stackoverflow.com/questions/14423959/tkinter-inserting-text-into-canvas-windows