In Python Tkinter, how do I get the index of an image embedded in a text widget using the name?

543 views Asked by At

I am creating an app using Python Tkinter in which I give the users an option to insert an image into a text widget. I know that when you insert an image, and you don't specify the name attribute, tkinter automatically generates one. There is also a way to get a tuple of all the names in the text widget using the text.image_names() method. All the methods I have looked at, that relate to text widget images only take the image's index as an attribute. However, I don't know the image's index.

It would be nice if anyone could tell me if there is a method where I give the function the image's name is an attribute, and get the index in return.

1

There are 1 answers

0
acw1668 On BEST ANSWER

You can use Text.index() on the image name to get the image index in "line.column" format.

Below is an example:

import tkinter as tk

root = tk.Tk()

text = tk.Text(root, width=80, height=20)
text.pack()

text.insert('end', 'This is line 1\n')
text.insert('end', 'Embed an image ')
img = tk.PhotoImage(file='sample.png')
text.image_create('end', image=img, name='img1')
text.insert('end', ' in a line')

print('Image with name "img1" is at index', text.index('img1'))

root.mainloop()

You will get Image with name "img1" is at index 2.15 in the console.