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

วิธีเปลี่ยนสีคำเฉพาะใน Tkinter Text Widget


ภาพรวม

Tkinter Text Widgets ใช้สร้างและแสดง Multiline Text Input มีฟังก์ชันและเมธอดหลายอย่าง Config Text Widget สมมติต้องการเปลี่ยนสีคำเฉพาะ ใช้เมธอด tag_add(tag name, range) เลือกคำที่ต้องการ Format แล้วใช้ tag_config(properties) เปลี่ยนสี พื้นหลัง และ Property อื่นๆ

ตัวอย่างโค้ด

# Import required libraries
from tkinter import *
# Create an instance of tkinter window
win = Tk()
# Define the geometry of the window
win.geometry("600x250")
# Create a text widget
text = Text(win)
text.insert(INSERT, "Hello World!\n")
text.insert(END, "This is a New Line")
text.pack(fill=BOTH)
# Configure the text widget with certain color
text.tag_config("start", foreground="red")
text.tag_add("start", "1.6", "1.12")
win.mainloop()

ผลลัพธ์

รันโค้ดจะแสดงหน้าต่างพร้อม Text ที่มี String "Hello World" โดย "World" มีสีเฉพาะ

วิธีเปลี่ยนสีคำเฉพาะใน Tkinter Text Widget