3
这是(我假设)一个基本问题,但我似乎无法弄清楚。PyGame局部变量
考虑下面的代码:
from src.Globals import *
import pygame
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# This is a list of 'sprites.'
block_list = pygame.sprite.Group()
def update_screen():
# Loop until the user clicks the close button.
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Clear the screen
screen.fill(WHITE)
for i in blocks:
block_list.add(block)
block_list.draw(screen)
# Limit to 20 frames per second
clock.tick(20)
# Update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
,一切工作正常。我可以在线程中调用函数update_screen
并使其正常工作。但是,如果我移动done = False
这个函数声明的,然后我得到的错误:UnboundLocalError: local variable 'done' referenced before assignment.
我的问题是:为什么是我可以放心地有clock
,并且block_list
以外的功能,但不done
?
您需要在函数的顶部声明'全球done'因此荣获:
您可以通过以下网址获取更多不是一个局部变量。您不需要使用'clock'和'block_list'来完成这个工作,因为您不需要为它们赋值并仅引用它们的当前值。 – martineau
我发现使用全球实际上使其全球化将有所帮助。你的解释有助于说清楚为什么:因为我没有改变其他的价值观。 – Teknophilia
Python遵循所谓的[LEGB规则](http://stackoverflow.com/a/292502/355230)来查找变量(并在分配时确定它们是否是本地的)。 – martineau