I'm trying to print the key used to press a button.
How do you extract the char from the event (eg. <KeyPress event keysym=1 keycode=49 char='1' x=95 y=34 >
)
What I've got so far:
from tkinter import Button, Frame, Tk
class ButtonCreator:
def __init__(self, master, num, options):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text=str(num) + ' ' + str(options[num-1]),
command=self.func)
self.button.pack(side='left')
master.bind(str(num), self.func)
def func(self, occur, _event=None):
print(occur) # <- num is event, not char
print(options[occur-1]) # <- failing here: TypeError: list indices must be
# integers or slices, not Event
options = ['one', 'two', 'three']
button_count = len(options)
root = Tk()
for j in range(button_count):
abc = ButtonCreator(root, j+1, options)
root.mainloop()
Edit: Solved my issue. Instead of using
options[occur-1]
I should be using
options[int(occur.char)-1]