Python 函数忽略变量变化
Python function ignores variable change
我正在使用 python 制作一个基本的 2 屏应用程序,并通过更改变量来切换屏幕(是的,我知道这是制作应用程序的一种非常糟糕的方法)我正在使用 pygame
我有一个基本的主函数,它检测某个键何时按下,然后将变量设置为 2,然后运行我的绘图函数,它有一个 if 语句来判断变量是 1 还是 2。呈现不同的东西。
我的问题是,即使事件更改了变量(然后打印该变量以验证它已更改),我的输出也没有改变,我可以更改我设置为默认值的变量并将其更改为另一个屏幕,但它拒绝从事件中更改。
import pygame
import time
import datetime
from pygame import freetype
screen = 1 <<-- My default value for the screen
FPS = 15
WHITE = (220, 220, 220)
WIDTH, HEIGHT = 480, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.init()
pygame.display.set_caption("test")
FONT = pygame.freetype.Font("FiraSans-Medium.ttf", 150)
def draw(): <<-- Draw Function
if screen == 1:
print("screen 1")
now = datetime.datetime.now()
current_time = now.strftime("%I:%M")
WIN.fill(WHITE)
FONT.render_to(WIN, (20, 160), current_time, (0, 0, 0))
pygame.display.update()
if screen == 2:
print("screen 2")
WIN.fill(WHITE)
FONT.render_to(WIN, (20, 160), "screen 2", (0, 0, 0))
pygame.display.update()
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: <<-- Event to change the screen
screen = 2
print(screen)
draw() <<-- Call draw function
pygame.quit()
if __name__ == "__main__":
main()
函数认为screen是一个局部变量,只能在函数中使用。把global screen
放在函数的最前面,告诉函数screen,是一个全局变量,修改全局值。
我正在使用 python 制作一个基本的 2 屏应用程序,并通过更改变量来切换屏幕(是的,我知道这是制作应用程序的一种非常糟糕的方法)我正在使用 pygame
我有一个基本的主函数,它检测某个键何时按下,然后将变量设置为 2,然后运行我的绘图函数,它有一个 if 语句来判断变量是 1 还是 2。呈现不同的东西。
我的问题是,即使事件更改了变量(然后打印该变量以验证它已更改),我的输出也没有改变,我可以更改我设置为默认值的变量并将其更改为另一个屏幕,但它拒绝从事件中更改。
import pygame
import time
import datetime
from pygame import freetype
screen = 1 <<-- My default value for the screen
FPS = 15
WHITE = (220, 220, 220)
WIDTH, HEIGHT = 480, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.init()
pygame.display.set_caption("test")
FONT = pygame.freetype.Font("FiraSans-Medium.ttf", 150)
def draw(): <<-- Draw Function
if screen == 1:
print("screen 1")
now = datetime.datetime.now()
current_time = now.strftime("%I:%M")
WIN.fill(WHITE)
FONT.render_to(WIN, (20, 160), current_time, (0, 0, 0))
pygame.display.update()
if screen == 2:
print("screen 2")
WIN.fill(WHITE)
FONT.render_to(WIN, (20, 160), "screen 2", (0, 0, 0))
pygame.display.update()
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: <<-- Event to change the screen
screen = 2
print(screen)
draw() <<-- Call draw function
pygame.quit()
if __name__ == "__main__":
main()
函数认为screen是一个局部变量,只能在函数中使用。把global screen
放在函数的最前面,告诉函数screen,是一个全局变量,修改全局值。