![](/img/trans.png)
[英]How do I get the current length of the Text in a Tkinter Text widget
[英]In Python Tkinter, how do I get the index of an image embedded in a text widget using the name?
我正在使用 Python Tkinter 創建一個應用程序,其中我為用戶提供了將圖像插入文本小部件的選項。 我知道當你插入一張圖片並且你沒有指定name
屬性時,tkinter 會自動生成一個。 還有一種方法可以使用text.image_names()
方法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 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()
您將在控制台中獲得Image with name "img1" is at index 2.15
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.