w2019py
w2019py

Reputation: 3

Calling Objects and Passing Variables in Python Pygame Not Working Error Says Variable Not Defined

I'm a bit confused as to how objects and passing work in Python. I would like to make an object to call functions of a class, but I can't seem to get the mainWindow variable to pass. I keep getting an error saying mainWindow has not been defined

I made a program in TKinter years ago and had everything within a main method and after each function was finished it would call the next function and pass variables. I wanted to see if I could just do the same thing by calling functions through an object.

import pygame
pygame.init

class PreviewWindow:
    def __init__(self):
        mainWindow = pygame.display.set_mode((800, 600))
        pygame.display.set_caption('Sprite Viewer')

    def loadImage(self, mainWindow):
        userImage = pygame.image.load('well.png')
        imageSize = userImage.get_rect()

    def drawImage(self, userImage, imageSize):
        mainWindow.blit(userImage, imageSize)
        pygame.display.flip()

previewObj = PreviewWindow
previewObj.loadImage(mainWindow)
previewObj.drawImage(mainWindow, userImage, imageSize)

I want to understand how to call functions within classes while being able to pass variables and functions to said functions.

Upvotes: 0

Views: 78

Answers (1)

Calder White
Calder White

Reputation: 1326

There's a couple of things going on here. First of all, you are defining mainWindow within the __init__ function's scope. This means it cannot be referenced from outside the function. You are using OOP correctly until you begin passing mainWindow into your class's methods. Instead, just use the mainWindow that is defined already by __init__!

You can do this by setting self.mainWindow. self makes the property object specific.

import pygame
pygame.init

class PreviewWindow:
    def __init__(self):
        # initialize your mainWindow
        self.mainWindow = pygame.display.set_mode((800, 600))
        pygame.display.set_caption('Sprite Viewer')

    def loadImage(self, imageName):
        self.userImage = pygame.image.load(imageName)
        self.imageSize = userImage.get_rect()

    def drawImage(self):
        # use the mainWindow you initialized in __init__
        self.mainWindow.blit(self.userImage, self.imageSize)
        pygame.display.flip()

previewObj = PreviewWindow()
previewObj.loadImage('well.png')
previewObj.drawImage()

Upvotes: 1

Related Questions