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

Highlight dòng hiện tại trong Text widget Tkinter

Text widget Tkinter nhập nhiều dòng. Để highlight dòng đang chọn, dùng tag_add() thêm tag cho range text, tag_configure() đặt background/foreground.

Ví dụ

from tkinter import *

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

text = Text(win, width=80, height=15, font=('Calibri 12'))
text.insert(INSERT, "Tkinter is a Python Library to create GUI-based applications.")
text.insert(END, "Learning Tkinter is Awesome!!")

# Highlight ký tự 1-7 dòng 1 ("Tkinter")
text.tag_add("start", "1.0", "1.7")
text.tag_configure("start", background="OliveDrab1", foreground="black")
text.pack()
win.mainloop()

Kết quả

Text widget với "Tkinter" (7 ký tự đầu) được highlight nền xanh lá nhạt (OliveDrab1), chữ đen.

Highlight dòng hiện tại trong Text widget Tkinter

Để highlight dòng hiện tại con trỏ: Bind <KeyRelease>, <ButtonRelease-1>, lấy text.index(INSERT), tính line number, tag_add line đó.