size/coordinates of wrapped text object in tkinter Canvas

家住魔仙堡 提交于 2021-01-29 12:32:50

问题


How do I get coordinates of a wrapped text object in Tkinter Canvas?

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.

I got this using canvas.bbox(text_object)

I want it to be like this :


回答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()



来源:https://stackoverflow.com/questions/63247399/size-coordinates-of-wrapped-text-object-in-tkinter-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!