1

When running my python app, pressing the keys does not produce a sound however once you exit the tkinter gui, it works and plays the sound. I tried to re position the code but then the GUI doesn't appear at all.

from Tkinter import *
import winsound
import pythoncom
import pyHook

root = Tk()
root.geometry("500x500")
root.title("Piano Keys")
photo = PhotoImage(file="food.gif")
picture = Label(root, image=photo)
picture.pack()
start = Button(root, text='Start Piano Keys')
close = Button(root, text='Exit Piano Keys', command=lambda:root.destroy())
close.pack()
root.mainloop()

def OnKeyboardEvent(event):
    key = event.Key
    if key == 'A':
        winsound.Beep(261, 200)
    if key == 'S':
        winsound.Beep(277, 200)
    if key == 'D':
        winsound.Beep(293, 200)
    if key == 'F':
        winsound.Beep(311, 200)
    if key == 'G':
        winsound.Beep(329, 200)
    if key == 'H':
        winsound.Beep(349, 200)
    if key == 'J':
        winsound.Beep(370, 200)
    if key == 'K':
        winsound.Beep(392, 200)
    if key == 'L':
        winsound.Beep(415, 200)
    return True

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
  • Is there a specific need for Pyhook here? As long as it has focus, your root window or any Tkinter widget can capture keyboard events. http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm – atlasologist May 09 '14 at 10:52

1 Answers1

1

You tried to reposition it how, exactly? mainloop starts the GUI, it should be called last, iirc. Except PumpMessages would block the thread, i think.. Mhm, here's a related question. So it's because the main thread is being blocked by mainloop, hence pyhook can't do it's stuff (yet).

Community
  • 1
  • 1