简体   繁体   English

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

[英]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.

相关问题 如何获取Tkinter Text小部件中Text的当前长度 - How do I get the current length of the Text in a Tkinter Text widget 如何将焦点放在python Tkinter文本小部件上? - How do I give focus to a python Tkinter text widget? 如何获取小部件的名称Python Tkinter - How to get the name of a widget Python Tkinter 在Python 2.6中使用Tkinter,如何使按钮小部件在文本框中打印出选中的Checkbuttons? - Using Tkinter in Python 2.6 how do I make a button widget print out selected Checkbuttons in a text box? 如何将用户输入放入文本小部件中并使用 Python 使用 tkinter 在日志文件中进行搜索 - How can I put user input inside text widget and do search in Log file with tkinter using Python 如何在 Tkinter 中获取小部件的名称? - How can I get the name of a widget in Tkinter? 如何在 tkinter 中获取小部件 position? - How do I get a widget position in tkinter? 如何让 tkinter 文本小部件识别索引中的行? - How do you make the tkinter text widget recognise lines in the index? Tkinter,Python:如何保存在“输入”小部件中输入的文本? 如何移动标签? - Tkinter, Python: How do I save text entered in the Entry widget? How do I move a label? 如何获取 Tkinter 文本小部件上右键单击事件的 line.column 索引? - How can I get the line.column index for the right-click event on Tkinter Text widget?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM