JoshW
JoshW

Reputation: 105

Tkinter printing key used to press button: How do I extract character from event?

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]

Upvotes: 1

Views: 212

Answers (2)

JoshW
JoshW

Reputation: 105

Instead of using options[occur-1] I should be using options[int(occur.char)-1] - as that outputs the specific character aspect of the event rather than the entire event.

Upvotes: 0

TheLizzard
TheLizzard

Reputation: 7710

Try this:

from tkinter import Button, Frame, Tk
from functools import partial


class ButtonCreator:
    def __init__(self, master, num, options):
        frame = Frame(master)
        frame.pack()
        self.num = num # Save the button number
        self.button = Button(frame, text=str(num) + ' ' + str(options[num-1]))
        self.button.pack(side='left')

        self.button.bind("<Button-1>", self.func)
        self.button.bind("<Button-2>", self.func)
        self.button.bind("<Button-3>", self.func)
        master.bind(str(num), self.func)

    def func(self, event):
        print("You pressed it with this key=", event.num)
        print("Button number =", self.num)
        print("Option chosen:", options[self.num-1])


options = ['one', 'two', 'three']
button_count = len(options)

root = Tk()
for j in range(button_count):
    abc = ButtonCreator(root, j+1, options)
root.mainloop()

I used <tkinter>.bind. For more info read this.

Upvotes: 2

Related Questions