-3

I am making a basic 2 screen application with python, and am switching screens by changing a variable (yes I am aware that this is a really bad way to make an app) I am using pygame

I have a basic main function that detects when a key is down, then sets the variable to 2, and then runs my draw function, that has an if statement for if the variable is 1 or 2. Renders a different thing.

My issue is that even with the event changing the variable (and then printing that variable verifying it changed) my output doesn't change, I can change the variable I set as my default value and it changes to the other screen, but it refuses to change from the event.

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()
  • You need to tell the main function that it's a global variable, otherwise it is treated as a local variable by default. Put `global screen` at the top of main. – John Gordon Jan 09 '22 at 03:20

1 Answers1

0

The function thinks screen is a local variable, only usable in the function. Put global screen at the top of the function to tell the function that screen, is a global variable, and modify the global value.

Shiv
  • 370
  • 1
  • 14