1

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)
Edward
  • 49
  • 2
  • 5

1 Answers1

5

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:

  • Using tag_add to make tag:

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)
  • Use window_create and bind for a widget:

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)
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
  • 1
    I went for the second option as I wasn't sure how referencing by index would work in a dynamic document. Anyway second option worked a treat thanks – Edward Jan 25 '23 at 14:03