spleen21
Posts: 4
Joined: Mon Dec 03, 2012 1:56 am

Trying to learn classes

Sun Mar 20, 2016 4:29 am

Hi everyone,

Im new to Python and trying to teach myself how to use classes. Im simply trying to load a white box using pygame from within a class so that i can eventually pass text to it. Problem is, for the life of me, i can't even draw a white box. I've tried all sorts of combinations but just keep getting error after error.

Ive can use pygame fine without using classes but just cant get anything to work while using them.

The code below tells me that there is no attribute called "screen". Did i not define it at the start?

Can someone please point me in the right direction?

Thanks

Code: Select all

import pygame

pygame.init()

white = (255, 255, 255)

screen = pygame.display.set_mode((800, 480))

class home():
    def __init__(self):
        self.screen.fill(white)

        
def main():

    runProgram = True
    
    clock = pygame.time.Clock()
    
    pygame.display.update()

    while runProgram:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False

        home()
        pygame.display.update()

main()
pygame.quit()

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Trying to learn classes

Sun Mar 20, 2016 8:56 am

In the scope of your class there isn't an attribute called screen.

You can either initially define the screen inside your class as self.screen or pass screen to the class initialise function. Or just use screen not self.screen.

If you want some examples of classes in pygame and python, try this code that I was involved in a few years ago
https://github.com/scotty3785/python-ai ... ic-control
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”