[英]UnboundLocalError: pygame music play and stop not working (on keydown)
I'm trying to play and stop a music in my main page. 我正在尝试在主页上播放和停止音乐。
It's kind of weird. 有点奇怪 From my code, if the user press "m", suppose, the music should be off.
从我的代码中,假设用户按“ m”,则应该关闭音乐。 However, the music didn't off.
但是,音乐并没有关闭。 It continue
它继续
UnboundLocalError: local variable 'music_playing' referenced before assignment
Can someone help me with my code? 有人可以帮我解决我的代码吗?
pickUpSound = pygame.mixer.music.load('test.mp3')
pygame.mixer.music.play(-1)
music_playing = True
def mainMenu():
main = pygame.image.load('menu.jpg')
screen.blit(main,(0,0))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == KEYDOWN:
if event.key == ord('m'):
if music_playing:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1)
music_playing = not music_playing
As it is written, event.type
should be simultaneously equal to KEYDOWN
and pygame.K_KP_ENTER
at the same time. 在编写时,
event.type
应该同时等于KEYDOWN
和pygame.K_KP_ENTER
。 The second should be event.key
instead of event.type
. 第二个应该是
event.key
而不是event.type
。
if event.key == pygame.K_KP_ENTER:
EDIT There seems to be something wrong with the "keypad enter" key, I commented the problematic line (maybe try with another key, for example, I used K_a, and was able to start/stop by pressing "a") 编辑 “键盘输入”键似乎出了点问题,我评论了有问题的行(例如,可以尝试使用另一个键,例如,我使用了K_a,并能够通过按“ a”键来启动/停止)
import pygame
def mainMenu():
pygame.display.init()
pygame.display.set_mode([128,128])
screen = pygame.display.get_surface()
#
pygame.mixer.init()
pickUpSound = pygame.mixer.music.load('test.mp3')
pygame.mixer.music.play(-1)
music_playing = True
#
main = pygame.image.load('menu.jpg')
screen.blit(main,(0,0))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
#if event.key == pygame.K_KP_ENTER:
if music_playing:
pygame.mixer.music.stop()
print "stopping"
else:
pygame.mixer.music.play(-1)
print "playing"
music_playing = not music_playing
mainMenu()
nb When running this code, I see the messages "playing" and "stopping" each time I press any key. nb运行此代码时,每次按任意键都会看到消息“正在播放”和“正在停止”。
With if event.key == pygame.K_a:
the music should start/stop by pressing "a". if event.key == pygame.K_a:
音乐应按“ a”开始/停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.