[英]Python won't let me use variable inside function
我不明白为什么它不能让我在函数内部使用display_w或display_h。 我无法在函数内部使用它,因为我不想在再次使用它时将其重置。 如何允许它使用这些变量?
import pygame
pygame.init()
display_w = 800
display_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)
def run():
print("Input your message: ")
msg = input()
print("Enter font size: ")
font_size = int(input())
display = pygame.display.set_mode((display_w, display_h))
pygame.display.set_caption("TextPos")
text_x = 0
text_y = 0
def message_to_screen(msg, color, font_size, x, y):
font = pygame.font.SysFont(None, font_size)
screen_text = font.render(msg, True, color)
display.blit(screen_text, [x, y])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
pygame.quit()
run()
if event.key == pygame.K_q:
print("Enter display width: ")
display_w = int(input())
print("Enter display height: ")
display_h = int(input())
running = False
message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
m_x, m_y = pygame.mouse.get_pos()
text_x = m_x
text_y = m_y
display.fill(white)
message_to_screen("X: %s" % m_x, black, 30, 10, 10)
message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
message_to_screen(msg, black, font_size, text_x, text_y)
message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)
pygame.display.update()
run()
在Python中,仅在函数内部引用的变量是隐式全局的。 如果在函数体内任何位置为变量分配了值,除非明确声明为全局变量,否则将假定该变量为局部变量。
尽管起初有些令人惊讶,但片刻的考虑可以解释这一点。 一方面,要求全局分配变量可防止意外副作用。 另一方面,如果所有全局引用都需要全局,那么您将一直使用全局。 您必须将对内置函数或导入模块的组件的每个引用声明为全局引用。 这种混乱将破坏全球宣言对确定副作用的有用性。
在您的情况下,您尝试在函数中设置变量,因此Python将其视为局部变量。
要将它们视为全局变量,请在本地定义它们时使用global
关键字,以指示您正在引用和修改函数范围之外的值。
将它们添加为参数?
def run(display_w, display_h):
一种访问变量的奇怪方法。 假设您的模块名称为xyz。 然后:
import xyz
def func():
xyz.display_w = 80
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.