1

enter image description here

How to create logic to set color for certain word like python shell in python tkinter for example if I type "import" is color should be blue and other stay remains same as given on image in the link above

2
  • 1
    StackOverflow is not a place to ask for code from scratch. You need to try it yourself and post the problem you came across.
    – figbeam
    Mar 1, 2022 at 9:03
  • 1
    It is the same question as your previous question.
    – acw1668
    Mar 1, 2022 at 9:32

1 Answer 1

0

NOTE: The code below is based on the following declarations -:

import tkinter as tk

root = tk.Tk()

root.geometry('400x300')
root.title('Widget(With Colored Keywords)')

text = tk.Text(root, background = '#1f1f14', foreground = 'white', insertbackground = 'white')
text.pack()

The behavior required can be achieved using tags in tkinter Text widget, you can find the position of the word using regex(pos and last_pos), and then define a tag based on the position.

We can add a tag to the text widget if we know the start and end position of the tag using tag_add method of the Text widget.

tkinter.Text.tag_add(tagname, start_pos, end_pos)

Note that the position arguments to passed must be in Text widget index format.

Further, we use tag_config method of the text widget to configure properties of the tag, in this case the foreground.

This tag can be then used to modify the foreground color property of the part of the text that is within that tag.

def check_for_keywords(keyword_dict) :
    for i in keyword_dict :
        text.tag_remove(i, '1.0', tk.END)
        
        pos = 1.0
        while 1:
            pattern = r'\m{}\M'.format(i)
            pos = text.search(pattern, pos, regexp = True, stopindex = tk.END)
            if not pos:
                break
            last_pos = '%s+%dc' % (pos, len(i))
            text.tag_add(i, pos, last_pos)
            pos = last_pos
        text.tag_config(i, foreground = keyword_dict[i])
    root.after(1000, check_for_keywords)
    return

Given a dictionary, with {keyword : color_name} mapping, a function can be made to check for keywords. Also note that this function will have to be called using the after method of the tkinter window every second(you can change the check timings based on the suitability of it with your project).

keyword_dict = {'label' : 'red', 'button' : 'blue', 'gml' : 'orange'}

root.after(1000, lambda : check_for_keywords(keyword_dict)) #Checks every one second.
root.mainloop()

The full code will become -:

import tkinter as tk

def check_for_keywords(keyword_dict) :
    
    for i in keyword_dict :
        text.tag_remove(i, '1.0', tk.END)
        
        pos = 1.0
        while 1:
            pattern = r'\m{}\M'.format(i)
            pos = text.search(pattern, pos, regexp = True, stopindex = tk.END)
            if not pos:
                break
            last_pos = '%s+%dc' % (pos, len(i))
            text.tag_add(i, pos, last_pos)
            pos = last_pos
        text.tag_config(i, foreground = keyword_dict[i])
    root.after(1000, lambda : check_for_keywords(keyword_dict))
    return

keyword_dict = {'label' : 'red', 'button' : 'blue', 'gml' : 'orange'} #GML CODING KEYWORDS TEST DICT

root = tk.Tk()

root.geometry('400x300')
root.title('Widget(With Colored Keywords)')

text = tk.Text(root, background = '#1f1f14', foreground = 'white', insertbackground = 'white')
text.pack()

root.after(1000, lambda : check_for_keywords(keyword_dict)) #Checks every one second.
root.mainloop()

Now, on typing any of the mentioned keywords, the keywords are highlighted -: OUTPUT


NOTE: Also more helpful information can be found here.

For more information on how to deal with tags, this might also be a useful resource.

10
  • sir can i put many keys to same value
    – Anmol
    Mar 1, 2022 at 11:37
  • @Anmol yes you can :)
    – typedecker
    Mar 1, 2022 at 11:38
  • @Anmol what error does it show?
    – typedecker
    Mar 1, 2022 at 12:14
  • @Anmol uhh ok..
    – typedecker
    Mar 1, 2022 at 12:19
  • when putting symbols like *,#,etc```` tkinter.TclError: couldn't compile regular expression pattern: quantifier operand invalid```
    – Anmol
    Mar 1, 2022 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.