Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่มขอบเขต (Outline) รอบข้อความบน Canvas ใน Tkinter


Widget Canvas ใน Tkinter ใช้หลายวัตถุประสงค์ เพิ่มภาพ, สร้างและวาดรูปทรง, แอนิเมชัน ฯลฯ ใช้ฟังก์ชันในตัวสร้างและแสดงข้อความ

สร้างข้อความใช้ create_text(x,y, text, **options) เพื่อเพิ่มขอบเขตรอบข้อความใน Canvas ต้องสร้าง bounding box รอบข้อความ คุณสมบัติ bounding box ลิงก์กล่องมองไม่เห็นกับ widget ทำให้สามารถวาดสี่เหลี่ยมรอบข้อความได้

สร้างสี่เหลี่ยม แล้วดึงไปไว้ด้านหลัง ทำให้ข้อความอยู่เหนือสี่เหลี่ยม สี่เหลี่ยมต้องมีคุณสมบัติ outline รอบ canvas item

ตัวอย่าง

# 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()

ผลลัพธ์

รันโค้ด จะแสดงหน้าต่างพร้อมข้อความกำหนดไว้ใน canvas ข้อความจะมีขอบเขตมองเห็นได้

วิธีเพิ่มขอบเขต (Outline) รอบข้อความบน Canvas ใน Tkinter