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

Cách tạo viền (outline) cho text trên Canvas Tkinter

Canvas.create_text() không có tham số outline. Cách làm: vẽ text, lấy bounding box (bbox), dùng bbox vẽ rectangle có outline.

Các bước

  • Tạo Canvas, set background.

  • Tạo text bằng create_text().

  • Lấy bbox: canvas.bbox(text_id).

  • Vẽ rectangle dùng bbox với outline="blue".

  • Chạy mainloop.

Ví dụ

from tkinter import *

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

canvas = Canvas(root, background="white")
canvas.pack(expand=True)

text = canvas.create_text(175, 50, text="Text inside the Canvas", font="Calibri, 20", fill="green")
bbox = canvas.bbox(text)
canvas.create_rectangle(bbox, outline="blue")

root.mainloop()

Kết quả

Text "Text inside the Canvas" có khung chữ nhật viền xanh.

Cách tạo viền (outline) cho text trên Canvas Tkinter