Search code examples
pythontkinterkeymapping

I want to map my tkinter buttons to keys on the numberpad, What am I doing wrong please?


Python noob here, I have a catalog of snacks from the vending machine, text to speech, and a back, next and current button.

I want to map my buttons to keys on the numberpad but it doesnt seem to be working. When the gui pops up, I can click the button and it will read the items on the list for me, but I want to be able to control it with the numberpad instead of using the mouse to click the buttons.

vl = ["donuts","cookies","spicy chips","mild chips","cheesy chips","mini donuts","Mrs. Freshlys Cupcakes","rubbery cake thing"]
import pyttsx3
engine = pyttsx3.init()
cupo = vl[0] # cupo is current position, 0 is the first entry in the vl list
def current():
       global cupo # cupo was defined outside of the function, therefore we call global
       engine.say(cupo)
       engine.runAndWait()


def back():
        global cupo
        pos = vl.index(cupo)
        if pos == 0: # pos is position
                engine.say(cupo)
                engine.runAndWait()
        else:
                prepo = int(pos) - 1 # prepo is previous position
                cupo = vl[prepo]
                engine.say(cupo)
                engine.runAndWait()


def next():
        global cupo
        pos = vl.index(cupo)
        if pos == (len(vl) - 1):
                engine.say(cupo)
                engine.runAndWait()
        else:
                nexpo = int(pos) + 1 # nexpo is next position
                cupo = vl[nexpo]
                engine.say(cupo)
                engine.runAndWait()

print('\n'.join(map(str,vl)))

import tkinter
import sys




window = tkinter.Tk()
window.title("GUI")

def vendy():
    tkinter.Label(window, text = "Vendy!").pack()

b1 = tkinter.Button(window, text = "Back", command = back).pack()
b2 = tkinter.Button(window, text = "Repeat", command = current).pack()
b3 = tkinter.Button(window, text = "Next", command = next).pack()

bind('/',back.func)
bind('*',current.func)
bind('-',next.func)

window.mainloop()


Solution

  • window.bind('/', back)
    window.bind('*', current)
    window.bind('-', next)
    

    An event parameter is passed to the functions so add an argument to them.

    Example:

    def back(event=None):
        ...