Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo viền (outline) cho text trên Canvas Tkinter

Canvas Tkinter vẽ text: create_text(x, y, text, **options). Để tạo outline (viền) cho text, dùng bounding box + rectangle.

Các bước: tạo text → lấy bbox → tạo rectangle trong bbox với outline → raise text lên trên rectangle.

Ví dụ

from tkinter import *

win = Tk()
win.geometry("700x350")

canvas = Canvas(win, bg="blue3")
canvas.pack()

text = canvas.create_text(100, 200, text="This works only in canvas", font=('Calibri 18'), anchor="w", fill="white")
bbox = canvas.bbox(text)
rect = canvas.create_rectangle(bbox, outline="yellow", fill="black", width=5)
canvas.tag_raise(text, rect)
win.mainloop()

Kết quả

Text trắng "This works only in canvas" trên nền đen, viền vàng chữ nhật bao quanh.

Tạo viền (outline) cho text trên Canvas Tkinter

Kỹ thuật: bbox() trả về (x1,y1,x2,y2) bao quanh text. create_rectangle() vẽ hình chữ nhật. tag_raise(text, rect) đưa text lên trên rectangle.