[英]Tkinter: I can't highlight text in text widget
因此,我使用tkinter
制作了一個文本編輯器,並使用tag_config
突出顯示語法。
代碼
#Importing modules
from tkinter import *
#Main Window
Window = Tk()
Window.minsize(400, 550)
##Main Script
#Defs
#Main frame
main = Frame(Window)
#Main text widget
text = Text(main, bd=0, highlightthickness=0, borderwidth=0, bg="#323232", fg="white")
#Configs
text.config(width=55, height=35)
main.config(width=55, height=35)
#Tag config for coloring syntax
text.tag_configure("import", foreground="yellow")
Window.update()
#Packs and places
#main.place(anchor="c", rely=.5, relx=.5)
main.pack(expand=True, fill=BOTH, side="right")
text.pack(expand=True, fill=BOTH)
#Update window
Window.update()
#Window.mainloop()
Window.mainloop()
問題
tag_configure
在第 23 行不起作用text.tag_configure("import", foreground="yellow")
問題
有沒有辦法解決這個問題? 或者有什么方法可以突出顯示 tkinter 中的文本?
編輯
我加
def check_syntax(event):
text.tag_add('import', 1.0, END)
text.bind("<Return>", check_syntax)
在代碼上但有 1 個問題,當我運行代碼並在文本小部件中鍵入import tkinter
進行測試並按輸入時,“tkinter”也突出顯示
如何解決?
我相信原因是您需要首先使用 tag_add function 添加標簽。 您應該閱讀其他類似問題的問題。 我自己嘗試了代碼,它可以工作。 (你必須在完成一行后按回車)
tag_configure
只配置一個標簽,它不會將該標簽應用於文本范圍。 要使用標簽,您需要調用tag_add
並給它一個開始和結束索引。 那,或者在調用insert
時添加標簽。
例如,這顯示了如何插入一些文本,然后將突出顯示應用於幾個字符:
text.insert("end", "import foo\nimport bar\n")
text.tag_add("import", "1.0", "1.6")
text.tag_add("import", "2.0", "2.6")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.