You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于树莓派制作键盘时遇AttributeError错误求助

Fixing the "AttributeError: event member not defined" in Your Raspberry Pi MIDI Keyboard Project

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

  1. Add Event Type Checks First
    Make sure your keypress() function only processes KEYDOWN (or KEYUP) 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 None
    

    This ensures you never try to access event.key on an event that doesn't support it.

  2. 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 original keypress() function likely includes this filtering step, so compare your version line-by-line to spot where you deviated.

  3. 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 QUIT event) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:43:17