Search code examples
tkintertkinter-canvastkinter-layout

Annotate an image in tkinter canvas window dynamically


So I am displaying an image using canvas in my Tkinter window. Now I have a button which calculates certain parameters and I want that to be displayed dynamically over the image. So basically after each calculation, the annotations should change to new parameters.

e.g. Consider that I am calculating column dimensions, and after each calculation, I have to display the dimensions marked on the respective sides of the column image that I have in my Tkinter window.

So is it possible to annotate the image dynamically and if not, is there any other way to perform this task?


Solution

  • Check the below example out

    from tkinter import *
    from PIL import Image,ImageTk
    import random
    
    def annotate():
        annotation=str(random.randint(1000,9999))
        canvas.itemconfig(annotation_text,text=annotation)
    
    root=Tk()
    
    canvas=Canvas(root)
    canvas.pack(fill='both',expand=True)
    
    image=Image.open('example.png')
    image=ImageTk.PhotoImage(image.resize((300,300)))
    canvas.create_image(150,150,image=image)
    
    annotation_text=canvas.create_text(50,50,text='')
    
    button=Button(root,text='Annotate',command=annotate)
    button.pack()
    
    root.mainloop()
    

    You can make use of the itemconfig method to configure the text. The above example will annotate the image at (50,50) with a random integer on click of a button.