So, maybe I just made too much work for myself and there's a really simple way to do this that I haven't found, but here's the solution I made to handle this, in case anyone else needs to do the same type of thing:
from Tkinter import Tk, Text
from tkFont import Font
class BlockyCursorText(Text):
def __init__(self, parent):
Text.__init__(self, parent, bg='black', fg='green', insertwidth=0,
font=Font(family='Courier', size=10))
# initialize the cursor position and the color of the cursor
self.cursor = '1.0'
self.switch = 'green'
self._blink_cursor()
self._place_cursor()
def _place_cursor(self):
'''check the position of the cursor against the last known position
every 15ms and update the cursorblock tag as needed'''
current_index = self.index('insert')
if self.cursor != current_index: # if the insertcursor moved
self.cursor = current_index # store the new index
self.tag_delete('cursorblock')# delete the cursorblock tag
start = self.index('insert') # get the start
end = self.index('insert+1c') # and stop indices
if start[0] != end[0]: # this handles an index that
self.insert(start, ' ') # reaches the end of the line
end = self.index('insert') # by inserting a space
self.tag_add('cursorblock', start, end) # add the tag back in
self.mark_set('insert', self.cursor) # move the insertcursor
self.after(15, self._place_cursor)
def _blink_cursor(self):
'''alternate the background color of the cursorblock tagged text
every 600 milliseconds'''
if self.switch == 'green':
self.switch = 'black'
else:
self.switch = 'green'
self.tag_config('cursorblock', background=self.switch)
self.after(600, self._blink_cursor)
if __name__ == '__main__':
root = Tk()
text = BlockyCursorText(root)
text.pack()
text.insert('1.0', 'hello world')
root.mainloop()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…