'I want to get a way to highlight code using the python Tkinter Text control
I want to implement a code highlighting function, but I don't know how to use this tk.Text
。 (not necessarily python, of course)
I hope to get a highlighted function f (x, y, z, a)
whose function is to highlight it into the a color from row x, column y to column z. Then I also hope that every time the user enters in the text control, I can receive a message and call the another function t (x, y)
to update the highlighted content. I hope to get this kind of writing.
In addition, I don't want to use a third-party library to solve this problem. My reference code is as follows. You can modify my code to answer this question.
Reference code:
import tkinter as tk
window = tk.Tk()
window.geometry('600x600')
window.configure(bg='white')
content = tk.Text(window, relief='solid', font=('Consolas', 12))
content.pack()
content.place(x=15, y=15, width=570, height=535)
window.mainloop()
My English is not very well. I use machine to translate my text, so it may contain some low-level errors.
Thanks!
Solution 1:[1]
You should use search function to search the first index of you word and then use this "%s+%sc"%(starting_index(that you will find with the help of search function),length of your word)
if you don't want to download any external module then I suggest you to use idlelib this is a build in module
you can try this:-
import tkinter as tk
def highight_function(code_list):
for i in code_list:
content.tag_remove(i,"1.0",tk.END)
starting_index = 1.0
while True:
pattern = r"\m{}\M".format(i)
starting_index = content.search(pattern,starting_index,regexp=True,stopindex=tk.END)
if not starting_index:
break
last_index = "%s+%sc"%(starting_index,len(i))
content.tag_add(i,starting_index,last_index)
starting_index = last_index
content.tag_configure(i,foreground=code_list[i])
window.after(1000,lambda :highight_function(code_list))
window = tk.Tk()
code_list = {"from":"cyan","as":"cyan","import":"cyan"}
window.geometry('600x600')
window.configure(bg='white')
content = tk.Text(window, relief='solid', font=('Consolas', 12))
content.pack()
content.place(x=15, y=15, width=570, height=535)
window.after(1000,lambda :highight_function(code_list))
window.mainloop()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Coder |