Pages

duminică, 17 mai 2026

PyGame : simple example python script to toggle fullscreen mode.

Simple example with pygame window to switch on fullscren.
The program starts by initializing Pygame and creating a 640×480 window. It also prepares a font and draws a button on the screen that will be used to toggle fullscreen mode. A variable keeps track of whether the program is currently in fullscreen or windowed mode.
Inside the main loop, the program listens for events. If the user clicks the button or presses the F12 key, the program switches between fullscreen and windowed display modes by recreating the Pygame window with the appropriate settings.
Every frame, the screen is cleared, the button is drawn, and the instruction text "use button or F12 key to switch on fullscreen" is displayed.
The window updates continuously at 60 FPS, so the fullscreen toggle feels instant and smooth.
Let's see the source code.
import pygame
import sys

pygame.init()

# Dimensiuni fereastră
WIDTH, HEIGHT = 640, 480
windowed_size = (WIDTH, HEIGHT)

# Moduri de afișare
screen = pygame.display.set_mode(windowed_size)
pygame.display.set_caption("Fullscreen Toggle Example")

# Font
font = pygame.font.SysFont("Arial", 22)

# Buton fullscreen
button_rect = pygame.Rect(20, 20, 200, 50)

# Stare fullscreen
is_fullscreen = False


def toggle_fullscreen():
    global screen, is_fullscreen

    is_fullscreen = not is_fullscreen

    if is_fullscreen:
        screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
    else:
        screen = pygame.display.set_mode(windowed_size)


# Loop principal
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # Click pe buton
        if event.type == pygame.MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):
                toggle_fullscreen()

        # Tasta F12
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_F12:
                toggle_fullscreen()

    # Fundal
    screen.fill((30, 30, 30))

    # Desenare buton
    pygame.draw.rect(screen, (70, 130, 180), button_rect)
    btn_text = font.render("Toggle Fullscreen", True, (255, 255, 255))
    screen.blit(btn_text, (button_rect.x + 10, button_rect.y + 12))

    # Text instrucțiuni
    info_text = font.render("use button or F12 key to switch on fullscreen", True, (255, 255, 0))
    screen.blit(info_text, (20, HEIGHT - 40))

    pygame.display.flip()
    clock.tick(60)