基于树莓派制作键盘时遇AttributeError错误求助
Hey there! Let's break down why you're hitting this error while building your MIDI keyboard on Raspberry Pi. That AttributeError on event.key means the event object you're trying to access doesn't actually have a key property—and that's almost always because you're trying to process a non-keyboard event by mistake.
What's Causing This?
In Pygame, not every event comes with a key attribute. For example, window QUIT events or mouse events don't include this property. If your keypress() function isn't filtering for only keyboard events before accessing event.key, it'll throw this error as soon as a non-keyboard event pops up in the event queue.
Step-by-Step Fixes
Add Event Type Checks First
Make sure yourkeypress()function only processesKEYDOWN(orKEYUP) events before trying to get the key name. Here's how that should look:def keypress(): for event in pg.event.get(): # Only handle actual key press events if event.type == pg.KEYDOWN: return pg.key.name(event.key) # Don't forget to handle quit events to avoid hanging the program if event.type == pg.QUIT: pg.quit() sys.exit() return NoneThis ensures you never try to access
event.keyon an event that doesn't support it.Cross-Check with the Original Repository Code
Chances are you accidentally removed or modified the event type check when copying/adapting the code from the repository. The originalkeypress()function likely includes this filtering step, so compare your version line-by-line to spot where you deviated.Debug with Event Logging
If you're still stuck, add a print statement right before the error line to see exactly what events are coming through:print(f"Event type: {event.type}, Event details: {event}") key = pg.key.name(event.key)This will show you which event is causing the issue (like a
QUITevent) so you can adjust your filtering logic accordingly.
Quick Note
Double-check that you've initialized Pygame properly with pg.init() at the start of your script—while this error isn't directly related to initialization, it's always a good foundational check to rule out other issues.
内容的提问来源于stack exchange,提问作者simoon99

