python - 在这段代码中,我得到 UnboundLocalError: local variable 'click' referenced before assignment。我不知道为什么?
问题描述
这是代码,有时它不会出现此错误,尽管有时会出现。如果我在代码永远无法工作之前引用变量。我在使用之前放置了 click = True 和 click = False ,它们都不起作用。
def main_menu():
while True:
screen.fill((255, 255, 255))
draw_text('K F C', font, (0, 0, 0), screen, 170, 20)
mx, my = pygame.mouse.get_pos()
button_1 = pygame.Rect(30, 400, 500, 100)
button_2 = pygame.Rect(650, 400, 500, 100)
button_3 = pygame.Rect(340, 600, 500, 100)
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
pass
if button_3.collidepoint((mx, my)):
if click:
pygame.quit()
pygame.draw.rect(screen, (255, 0, 0), button_1)
draw_text('Play Game', font_2, (0, 0, 0), screen, 90, 415)
pygame.draw.rect(screen, (255, 0, 0), button_2)
draw_text('Manual', font_2,(0, 0, 0), screen, 770, 415)
pygame.draw.rect(screen, (255, 0, 0), button_3)
draw_text('Quit', font_2,(0, 0, 0), screen, 525, 615)
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
mainClock.tick(60)
解决方案
那是因为你没有声明click
。您必须在click = #something
之前插入某处if click:
,如下所示:
def main_menu():
click = False # <------------------
while True:
screen.fill((255, 255, 255))
draw_text('K F C', font, (0, 0, 0), screen, 170, 20)
mx, my = pygame.mouse.get_pos()
button_1 = pygame.Rect(30, 400, 500, 100)
button_2 = pygame.Rect(650, 400, 500, 100)
button_3 = pygame.Rect(340, 600, 500, 100)
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
pass
if button_3.collidepoint((mx, my)):
if click:
pygame.quit()
pygame.draw.rect(screen, (255, 0, 0), button_1)
draw_text('Play Game', font_2, (0, 0, 0), screen, 90, 415)
pygame.draw.rect(screen, (255, 0, 0), button_2)
draw_text('Manual', font_2,(0, 0, 0), screen, 770, 415)
pygame.draw.rect(screen, (255, 0, 0), button_3)
draw_text('Quit', font_2,(0, 0, 0), screen, 525, 615)
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
mainClock.tick(60)
推荐阅读
- acumatica - 如何启用网格页脚 SummaryType?
- mysql - 从mysql中的子ID获取父ID的详细信息
- sql - 触发器函数中的 Postgresql 语法错误
- c# - 在运行时选择正确的 DLL 引用版本
- javascript - 如何创建用于云函数或 docker 的通用代码模块
- python - 从 json 文件中提取时出现 Python 和 JSON 错误
- sql - 在 Excel 密码保护的工作表上运行 SQL。连接问题
- reinforcement-learning - Ray RLllib:供外部使用的出口政策
- r - ggplot中传说中的希腊字母
- wordpress - 如何让一个静态 HTML 文件正常访问,不让 WordPress 运行?