create_text วิธีการของวิดเจ็ต Canvas ใน Tkinter ไม่มีแอตทริบิวต์เช่น "โครงร่าง" หรือ "เส้นขอบ" เพื่อกำหนดเค้าร่างรอบวัตถุข้อความ ดังนั้น ในการใส่โครงร่างบนข้อความแคนวาส คุณสามารถทำตามขั้นตอนด้านล่าง -
ขั้นตอน -
-
นำเข้าไลบรารีที่จำเป็นและสร้างอินสแตนซ์ของเฟรม tkinter
-
กำหนดขนาดของเฟรมโดยใช้ root.geometry วิธีการ
-
สร้างวิดเจ็ต Canvas และตั้งค่าความสูงและความกว้าง นอกจากนี้ ให้ตั้งค่าสีพื้นหลังด้วย background="white" .
-
ถัดไป สร้าง ข้อความ วัตถุภายใน Canvas โดยใช้ create_text() กระบวนการ. กำหนดแบบอักษรและสีของข้อความ ตามที่แสดงในตัวอย่าง
-
รับกล่องขอบเขต (bbox ) ของรายการข้อความ
-
ใช้ bbox data เพื่อสร้างสี่เหลี่ยมที่มีเค้าร่าง
-
สุดท้าย เรียกใช้ mainloop ของหน้าต่างแอปพลิเคชัน
ตัวอย่าง
# Import tkinter library
from tkinter import *
# Create an instance of tkinter frame or window
root = Tk()
# Set the geometry of tkinter frame
root.geometry("700x350")
# Create a Canvas
canvas = Canvas(root, background="white")
canvas.pack(expand=True)
# Create text inside the Canvas
text = canvas.create_text(175, 50, text="Text inside the Canvas", font="Calibri, 20", fill="green")
# Get the bounding box of text
bbox = canvas.bbox(text)
# Outline the canvas text
canvas.create_rectangle(bbox, outline="blue")
root.mainloop() ผลลัพธ์
เมื่อดำเนินการ มันจะสร้างผลลัพธ์ต่อไปนี้ -
