Hi!

I am kind of new at pygame and I can't use functions.
I define the "screen" variable outside of all functions(the "screen" variable is the "window"), and I can't use it in functions. I know it has to be global, but that won't work. Anyway the best i can give you is the code(it's from 2 files, but it is the same if I am just using one file and a function in that file).

Btw, the error is this
NameError: global name 'screen' is not defined


Here is the code for the "main" file

import sys, os
import pygame
from pygame.locals import *

import question

pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode((640, 400))
screen.fill((255, 80, 80))

question.question("hej", "a", "b", "c", "d")

pygame.display.update()

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

And here is the code for the file with the function that doesn't work

import sys, os
import pygame
from pygame.locals import *

pygame.init()

def question(q, a, b, c, d):
    font = pygame.font.Font(None, 50)

    q = font.render(q, True, (255, 255, 255))
    q_rect = q.get_rect()
    q_rect.centerx = screen.get_rect().centerx
    q_rect.top = 50

    a = font.render(a, True, (255, 255, 255))
    a_rect = a.get_rect()
    a_rect.centerx = screen.get_rect().centerx
    a_rect.top = 100

    b = font.render(b, True, (255, 255, 255))
    b_rect = b.get_rect()
    b_rect.centerx = screen.get_rect().centerx
    b_rect.top = 150

    c = font.render(b, True, (255, 255, 255))
    c_rect = c.get_rect()
    c_rect.centerx = screen.get_rect().centerx
    c_rect.top = 200

    d = font.render(b, True, (255, 255, 255))
    d_rect = d.get_rect()
    d_rect.centerx = screen.get_rect().centerx
    d_rect.top = 250

    screen.blit(q, q_rect)
    screen.blit(a, a_rect)
    screen.blit(b, b_rect)
    screen.blit(c, c_rect)
    screen.blit(d, d_rect)

You could add screen as one more argument to function question(q, a, b, c, d, screen).

Thank you so much!

I actually had another problem too(a code mistake), "b" is not supposed to be in the "c" and "d" text(lol), but i fixed it and everything works now. Thank you bumsfeld.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.