【问题标题】:Module 'pygame' has no 'K_SPACE' member模块“pygame”没有“K_SPACE”成员
【发布时间】:2020-03-08 15:04:39
【问题描述】:

我正在尝试使用混音器来播放一些音乐来暂停一首歌曲,但我总是收到上述错误。我在 VS Code 中,没有名为 'pygame.py' 的额外文件,并且混音器工作正常。

Music_List = os.chdir(r'Ene\\Music')
Music_Loader = random.choice((os.listdir(Music_List)))
mixer.music.load(Music_Loader)
print("Now playing: " + Music_Loader)
mixer.music.play()
while pygame.mixer.music.get_busy():
    pygame.mixer.music.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.K_SPACE:
            pygame.mixer.pause
pygame.mixer.music.fadeout(20)
mixer.music.stop()

编辑:使用if event.key == pygame.key.K_SPACE: 有效,但现在出现“视频系统未初始化”错误。

【问题讨论】:

    标签: python pygame key audio-player mixer


    【解决方案1】:

    event.type 只有两个值KEYUPKEYDOWN。这就是您看到此错误的原因,因为event.type 没有K_SPACE。使用if event.key == pygame.K_SPACE:,您将不会收到此错误。

    【讨论】:

    • 我认为应该是pygame.mixer.pause()。您缺少括号。
    【解决方案2】:

    这是一个工作版本,看起来这应该是您正在寻找的。​​p>

    import os,pygame,random,sys,pygame.locals as pl
    pygame.init() # step 1 to fix the error, initialize (most) pygame modules
    pygame.mixer.init() # inizialize the mixer
    Music_List = os.chdir(r'C:\\PATH\\TO\\MUSIC\\FILE.mp3')
    Music_Loader = random.choice((os.listdir(Music_List)))
    pygame.mixer.music.load(Music_Loader)
    print("Now playing: " + Music_Loader)
    pygame.mixer.music.play()
    display = pygame.display.set_mode((200,100)) # step 2 to fix the error
    while pygame.mixer.music.get_busy():
        pygame.mixer.music.get_pos()
        for event in pygame.event.get():
            if event.type == pl.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pl.KEYDOWN:
                if event.key == pl.K_SPACE:
                    pygame.mixer.music.pause() # to stop it, you need to use "mixer.music.pause()"
    
    pygame.mixer.music.fadeout(20)
    pygame.mixer.music.stop()
    

    弹出这个错误的原因是pygame需要一个显示设置才能工作。 我现在没有办法不这样做。

    实际上,事件类型不仅仅是“KEYDOWN”和“KEYUP”。例如:“MOUSEBUTTONUP”、“VIDEORESIZE”等等。 https://www.pygame.org/docs/ref/event.html

    【讨论】:

    • pygame.init() 不起作用,VS Code 说它没有模块。
    • 我不得不对代码进行一些调整(否则我会在 VS Code 中出错),现在我收到一个错误消息,提示“'Event' object has no attribute 'key'”
    • 1.: 可能性:您的陈述不正确。 “event.key”需要比“event.type”高一级。 2. 可能性:并非每种类型都有一个关键参数。例如 pl.MOUSEBUTTONDOWN 使用“event.button”。
    【解决方案3】:

    您需要使用 pygame.init() 初始化 pygame。举个例子:

    import pygame
    pygame.init()
    
    rest of your code
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多