I'm wondering if it's possible to bind a tag, such as 'keyword'
, to a string, such as 'print'
to my Text
widget in Tkinter (Python).
I'd like to know this because I'm not sure how I can use regular expressions to connect to my Text widget, and it seems extremely over-complicated, so I was wondering if there was any normal way.
My current code (SyntaxHighlighting.py):
global lang
lang = 'py'
def highlighter_bind(obj):
# Bind a highlighting language to a text widget within obj.
# Notice that obj must be a Frame with a .root property being
# the root it is binded to, and a .text widget being where I
# can highlight the text.
#
# The lang variable must be specified as a string that
# contains the file extension of whatever you want to
# highlight.
#
# Supported languages:
# - py
def command(self):
# Sub command for highlighting, it's what will
# be "binded" to <Key>.
if lang == 'py':
print 'imported language py'
# This is to get all the contents from the Text widget (property).
t = o.text.get('1.0', END).split('\n')[0:len(o.text.get('1.0', END).split('\n')) - 1]
# Now loop through the text and find + add a tag to each of the line's contents, assuming that there is something to be found.
for i in range(0, len(t)):
# We use the try / except because search.group will return an error if it's a NoneType.
try:
# Now we need to search through the line and see if we can find print.
if search('print ', t[i]).group(0):
# Now, WHERE did we find print? I get confused there,
# because I have no idea where to find the index(es) of
# the string I found within a line. I use a regex to find the
# string, but how do I find where?
print "Ok!" # Temporary, just stating that I found it. It works.
except:
pass
else:
print 'unrecognized language:', lang
o.root.bind('<Key>', command)
Ideal code were it to actually work:
...
def command(self):
if lang == 'py':
obj.text.tag_match("print", 'keyword')
# And even better, using regex to match..
obj.text.tag_match("(if|elif|else)", 'keyword')
obj.text.tag_match("(not|and|or)", 'keyword')
obj.text.tag_match("(\+|-|*|/|**|%%)", 'keyword') # %% is to put a modulus in.