tkinter Canvas中包装的文本对象的大小/坐标 [英] size/coordinates of wrapped text object in tkinter Canvas
本文介绍了tkinter Canvas中包装的文本对象的大小/坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Tkinter画布中获取包装的文本对象的坐标?
How do I get coordinates of a wrapped text object in Tkinter Canvas?
我知道我可以使用 canvas.bbox(text_object)
,但是它只会给我框坐标.但是,如果文本是自动换行的,我需要在最后一行获取最后一个字符的坐标.
I know I can use canvas.bbox(text_object)
but it will give me only box coordinates.
But if the text is wrapped I need to get coordinates of last char in the last line.
我想在文本下放置一个多边形,以便仅使文本成为背景色.
I want to put a polygon under text so as to make background color for text only.
我使用 canvas.bbox(text_object)
我希望它像这样:
推荐答案
您可以使用 canvas.find_overlapping(x,y,x + 1,y + 1)
查找文本的边界:
You can use canvas.find_overlapping(x, y, x+1, y+1)
to find the boundaries of your text:
import tkinter as tk
def create_bg(item, bg='red'):
x0, y0, x1, y1 = canvas.bbox(item)
# start of last line
x = x0
y = y1 - 1
# find end x of last line
while x < x1 and item in canvas.find_overlapping(x, y, x + 1, y + 1):
x += 1
# find top y of last line
while y > y0 and item not in canvas.find_overlapping(x, y, x + 1, y + 1):
y -= 1
y += 1
vertices = [x0, y0, x1, y0, x1, y, x, y, x, y1, x0, y1]
bg = canvas.create_polygon(*vertices, fill=bg)
canvas.tag_lower(bg, item)
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
item = canvas.create_text(20, 20, anchor='nw', width=150,
text='This is an example of wrapped text.')
item2 = canvas.create_text(20, 120, anchor='nw', font='Arial 20', width=150,
text='This is an example of wrapped text.')
create_bg(item)
create_bg(item2, 'cyan')
root.mainloop()
这篇关于tkinter Canvas中包装的文本对象的大小/坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文