如何在 Tkinter 中高亮文字小部件的當前行?


我們可以使用 Tkinter text 小部件來接受多行使用者輸入。我們可以插入文字、顯示資訊以及從文字小部件中獲取輸出。

為了高亮文字小部件中當前選中的文字,我們可以使用 tag_add() 方法,它僅在當前文字中新增一個標籤。

示例

# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win=Tk()

# Set the geometry
win.geometry("700x350")

# Add a text widget
text=Text(win, width=80, height=15, font=('Calibri 12'))

# Set default text for text widget
text.insert(INSERT, "Tkinter is a Python Library to create GUI-based applications.")
text.insert(END, "Learning Tkinter is Awesome!!")

# Select Text by adding tags
text.tag_add("start", "1.0","1.7")
text.tag_configure("start", background="OliveDrab1", foreground="black")
text.pack()

win.mainloop()

輸出

執行上述程式碼將顯示一個帶有文字小部件的視窗,其中包含高亮顯示的文字。

更新於: 05-Aug-2021

1K+ 瀏覽次數

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.