简体   繁体   中英

Tkinter: I can't highlight text in text widget

So I made a text editor using tkinter and I used tag_config to highlight the syntax.

CODE

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

PROBLEM
The tag_configure is not working in line 23
text.tag_configure("import", foreground="yellow")

QUESTION
Is there a way to fix that? or Is there any way to highlighting text in tkinter?

EDIT
I add

def check_syntax(event):
    text.tag_add('import', 1.0, END)       

text.bind("<Return>", check_syntax)

on the code but there are 1 problem, when i run the code and type import tkinter in the text widget for test and press enter the "tkinter" is highlighted too
How to fix that?

I believe the reason is that you need to actually add a tag first using the tag_add function. You should read this other question with a similar problem. I tried out the code myself and it works. (You'll have to press enter after completing a line)

How to use tkinter tag_config? Python 3.7.3

tag_configure only configures a tag, it doesn't apply the tag to a range of text. To use the tag you need to call tag_add and give it a start and end index. That, or add the tag when calling insert .

For example, this shows how to insert some text, and then apply highlighting to a few characters:

text.insert("end", "import foo\nimport bar\n")
text.tag_add("import", "1.0", "1.6")
text.tag_add("import", "2.0", "2.6")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM