pythonimagetkintertkinter-text

I have managed to insert an image into a tkinter text widget but how to make it clickable?


The following code works as far as getting the image into the text widget but I want to be able to detect when it's clicked and although that last line of code doesn't generate any errors, it doesn't work either.

my_image = ImageTk.PhotoImage(file = path)
tag = txtbox.image_create(txtbox.index('insert'), image = my_image)
txtbox.tag_bind(tag, "<Button-1>", on_image_click)

Solution

  • I went through the documentation and could not find a way to associate tags with image_create directly. But there are at least two ways you could achieve this:

    You can use tag_add to add a tag to the images's index and then use it along with tag_bind

    index = txtbox.index('insert')
    txtbox.image_create(index, image=my_image)
    txtbox.tag_add('image', index)
    
    txtbox.tag_bind('image', '<Button-1>', on_image_click)
    

    Instead of using image_create, you can use a label to show the image and then do the binding on that label and display that label on the text widget with window_create

    label = Label(txtbox, image=my_image)
    
    txtbox.window_create(txtbox.index('insert'), window=label)
    label.bind('<Button-1>', on_image_click)