I wanted to create line numbers for my text editor, but it's a bit complicated: Tkinter adding line number to text widget
So I decided to create a line and column counter, like in the IDLE
. To achieve this goal, I decide to listen for the <Key>
event generated on a tkinter.Text
widget. I did not know which are the properties of an event object, so I decided to take a look in the source code of the Event
class (one of the best tutorials :D), and I discovered there are 2 main properties that are interesting for my goal, that is keycode
and char
.
My question is, are this keycodes
platform independents? I would like that my text editor work on all platforms without undefined behaviour, because of wrong interpretation of keycodes
.
This is a simple practical functional example of what I would like to do:
from tkinter import *
lines = 1
columns = 0
ARROWS = (8320768, 8124162, 8255233, 8189699)
def on_key_pressed(event=None):
global columns, lines
if event.keycode == 3342463: # return
if columns > 0 and lines > 0:
columns -= 1
if columns < 0: # decrease lines if columns < 0
columns = 0
lines -= 1
if columns == 0 and lines > 1:
lines -= 1
elif event.keycode == 2359309: # newline
columns = 0
lines += 1
else:
if event.keycode not in (ARROWS) and event.char != '':
columns += 1
print("Lines =", lines)
print("Columns =", columns, '\n\n')
print(event.keycode, ' = ', repr(event.char))
root = Tk()
text = Text(root)
text.pack(fill='both', expand=1)
text.bind('<Key>', on_key_pressed)
root.mainloop()
What are the problems of this approach (after answering my first question)?