วิดเจ็ต Tkinter Canvas สามารถใช้ได้หลายวัตถุประสงค์ เช่น การเพิ่มรูปภาพ การสร้างและการวาดรูปร่างในแคนวาส การทำให้รูปร่างและวัตถุเคลื่อนไหว เป็นต้น การใช้ฟังก์ชันและวิธีการของ Canvas ทำให้เราสามารถสร้างและแสดงข้อความได้
ในการสร้างข้อความ เราใช้ create_text(x,y, text, **options) กระบวนการ. ในการเพิ่มเค้าร่างรอบๆ ข้อความใน Canvas เราต้องสร้างกรอบล้อมรอบข้อความ คุณสมบัติ bounding box เชื่อมโยงกล่องที่มองไม่เห็นกับวิดเจ็ต และสิ่งนี้จะทำให้เราสามารถใส่สี่เหลี่ยมในข้อความได้
เมื่อเราสร้างรูปสี่เหลี่ยมผืนผ้าแล้ว เราสามารถดึงส่วนนี้ไปไว้ด้านหลังและสร้างข้อความที่อยู่เหนือรูปสี่เหลี่ยมผืนผ้าได้ สี่เหลี่ยมต้องมีคุณสมบัติเค้าร่างที่ล้อมรอบรายการผ้าใบ
ตัวอย่าง
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
# Create a canvas widget
canvas=Canvas(win, bg="blue3")
canvas.pack()
# Create a text in canvas
text=canvas.create_text(100,200, text="This works only in canvas",
font=('Calibri 18'), anchor="w", fill="white")
# Make the bounding-box around text
bbox=canvas.bbox(text)
# Create a rectangle inside the bounding box
rect=canvas.create_rectangle(bbox, outline="yellow",
fill="black", width=5)
# Make the text above to the rectangle
canvas.tag_raise(text,rect)
win.mainloop() ผลลัพธ์
หากเราจะเรียกใช้โค้ดข้างต้น ก็จะแสดงหน้าต่างที่มีข้อความที่กำหนดไว้ล่วงหน้าในแคนวาส ข้อความจะมีโครงร่างที่มองเห็นได้บนผืนผ้าใบ
