在PythonTkinter中,如何使用名称获取嵌入文本小部件中的图像索引



我正在使用Python Tkinter创建一个应用程序,在该应用程序中,我为用户提供了将图像插入文本小部件的选项。我知道,当您插入一个图像,并且没有指定name属性时,tkinter会自动生成一个。还有一种方法可以使用text.image_names()方法获得文本小部件中所有name的元组。我看过的所有与文本小部件图像相关的方法都只将图像的索引作为属性。但是,我不知道图片的索引。

如果有人能告诉我是否有一种方法,我给函数图像的name是一个属性,并得到索引作为回报,那就太好了。

您可以在图像名称上使用Text.index()来获得"line.column"格式的图像索引。

下面是一个例子:

import tkinter as tk
root = tk.Tk()
text = tk.Text(root, width=80, height=20)
text.pack()
text.insert('end', 'This is line 1n')
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()

您将在控制台中获得Image with name "img1" is at index 2.15

相关内容

最新更新