Python Forum
[Tkinter] Text.search() regexp not working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Text.search() regexp not working
#11
Using \y works with your code for me on python 3.9.4
https://www.tcl.tk/man/tcl8.4/TclCmd/re_syntax.htm#M54 Wrote:\y matches only at the beginning or end of a word
from tkinter import *
 
class Application(object):
 
    def __init__(self, main_win):
        self.main_win = main_win
 
def search(text_widget, keyword, tag):
    pos = '1.0'
    case_insensitive = '(?i)'
    whole_word_left = '\y'
    whole_word_right = '\y'
    while True:
        idx = text_widget.search(f'{case_insensitive}{whole_word_left}{keyword}{whole_word_right}', pos, "end-1c", regexp=True)
        if not idx:
            break
        print(idx)
        pos = '{}+{}c'.format(idx, len(keyword))
        text_widget.tag_add(tag, idx, pos)
 
def main():
    win = Tk()
    app = Application(win)
    win.geometry("800x600+1000+300")
 
    txt = Text(win, bg='cyan')
    txt.pack()
    txt.insert('end-1c', 'import\nimport time\nfrom time import sleep\nImpo signal\nImport sys\nimpo board\nimport busio\nImpo digitalio\nfrom digitalio import Direction, Pull\nfrom RPi import GPIO\n10from adafruit_mcp230xx.mcp23017 import MCP23017\n')
 
    txt.tag_config('passed', background='yellow')
    search(txt, 'impo', 'passed')
 
    win.mainloop()
 
if __name__ == '__main__':
    main()
Output:
4.0 6.0 8.0
Reply
#12
Yep, \y worked for me too. Much thanks.

I had to back down from python 3.9 to 3.6 (last month) because there is a notebook tab color bug in 3.9. My project uses tabs and I needed to change their colors.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Search data in treeview without search button TomasSanchexx 3 1,604 Aug-12-2023, 03:17 AM
Last Post: deanhystad
  [Tkinter] Paste Operation not working in Text Widget Code_Enthusiast 1 2,946 Sep-11-2019, 08:49 PM
Last Post: Larz60+
  [Tkinter] add search bar = search for input in all computer directory francisco_neves2020 15 10,910 Apr-14-2019, 07:29 PM
Last Post: francisco_neves2020

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020