[英]In Python Tkinter, how do I get the index of an image embedded in a text widget using the name?
I am creating an app using Python Tkinter in which I give the users an option to insert an image into a text widget.我正在使用 Python Tkinter 创建一个应用程序,其中我为用户提供了将图像插入文本小部件的选项。 I know that when you insert an image, and you don't specify the
name
attribute, tkinter automatically generates one.我知道当你插入一张图片并且你没有指定
name
属性时,tkinter 会自动生成一个。 There is also a way to get a tuple of all the name
s in the text widget using the text.image_names()
method.还有一种方法可以使用
text.image_names()
方法text.image_names()
文本小部件中所有name
的元组。 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.如果有人能告诉我是否有一种方法可以让函数将图像的
name
作为属性,并获取索引作为回报,那就太好了。
You can use Text.index()
on the image name to get the image index in "line.column"
format.您可以在图像名称上使用
Text.index()
以"line.column"
格式获取图像索引。
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.您将在控制台中获得
Image with name "img1" is at index 2.15
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.