Editing Text in tkinter

Question:

So I’ve passed a create_text variable to “text1”

text1 = UseCanvas(self.window, "text", width = 100, height = 100, text = "Goodbye")

Using:

self.create_text(20,25 width=100,  anchor="center", text =self.text, tags= self.tag1)

after passing it to another class.

How do I edit that text widget? I want it to say “Hello” instead of “Goodbye”. I’ve looked all over and I can do anything I want with it EXCEPT change the text.

Asked By: Marcel Marino

||

Answers:

You should use the itemconfig method of the canvas to modify the text attribute. You have to give to it an id of one or more canvas items. Here is a small working example that lets you change the text of one text object:

# use 'tkinter' instead of 'Tkinter' if using python 3.x
import Tkinter as tk 

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.button = tk.Button(self, text="Change text", command=self.on_change_text)
        self.canvas = tk.Canvas(self, width=400, height=400)

        self.button.pack(side="top", anchor="w")
        self.canvas.pack(side="top", fill="both", expand=True)

        # every canvas object gets a unique id, which can be used later
        # to change the object. 
        self.text_id = self.canvas.create_text(10,10, anchor="nw", text="Hello, world")

    def on_change_text(self):
        self.canvas.itemconfig(self.text_id, text="Goodbye, world")

if __name__ == "__main__":
    root = tk.Tk()
    view = Example(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()
Answered By: Bryan Oakley

You should assign the text to a variable(id):
then use this code edit the text:
canvas.itemconfig(your_text_id, text="New Text")

Answered By: Zico
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.