如何解决修复UnboundLocalError:在python / pygame中分配错误之前引用了局部变量'click'吗?
请帮助我解决此错误:UnboundLocalError:分配前已引用本地变量“ click” 我是pygame的新手,正在学习使用pygame编写游戏代码。我正在尝试为我的游戏创建一个包含两个按钮的主菜单:play_button和stats_button。播放按钮将运行尚未编码的game()函数。统计按钮将显示排行榜和其他内容。但是,它没有按预期进行。当我单击第一个红色按钮(播放按钮)时,它仍在主屏幕上且无任何响应。与统计按钮相同。另外,“ X”现在不会关闭游戏窗口。另外,现在我的问题中出现了错误!
代码:
#importing area
import pygame,sys
from pygame.locals import *
#---------------------------------------------------------------------------\
#switching on
pygame.init()
#---------------------------------------------------------------------------\
#on screen area
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("space.io")
icon_game = pygame.image.load(r"C:\Uv Pygame\code\ufo.png") #load icon,r is compulsory
pygame.display.set_icon(icon_game)
background_1 = pygame.image.load(r"C:\Uv Pygame\code\bg.jpg")
#----------------------------------------------------------------------------\
#essentials
run = True
game = False
stats = False
font = pygame.font.SysFont(None,100)
click = False
#----------------------------------------------------------------------------\
#time
clock = pygame.time.Clock()
#-----------------------------------------------------------------------------\
#core
def game():
game = True
while game:
screen.fill((255,255,255))
draw_text("GAME",font,(0,0),screen,195,80)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
game = False
def stats():
stats = True
while stats:
screen.fill((255,255))
draw_text("STATS",80)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
stats = False
def draw_text(text,color,surface,x,y):
textobj = font.render(text,1,color)
textrect = textobj.get_rect()
textrect.topleft = (x,y)
surface.blit(textobj,textrect)
#------------------------------------------------------------------------------\
def main_menu():
while run:
screen.fill((255,255))
draw_text("HOME",80)
play_button = pygame.Rect(210,200,180,50)
stats_button = pygame.Rect(210,300,50)
pygame.draw.rect(screen,(255,play_button)
pygame.draw.rect(screen,stats_button)
mx,my = pygame.mouse.get_pos()
if play_button.collidepoint((mx,my)):
if click:
game()
if stats_button.collidepoint((mx,my)):
if click:
stats()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
main_menu()
错误:
Traceback (most recent call last):
File "C:\Uv Pygame\code\pract_1.py",line 95,in <module>
main_menu()
File "C:\Uv Pygame\code\pract_1.py",line 78,in main_menu
if click:
UnboundLocalError: local variable 'click' referenced before assignment
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。