Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame and Classes

So I'm making a tkinter/pygame game in classes and python doesn't recognise pygame when it is in a class. (don't worry about how i'm going to start up the windows separately, that will be done once the window works

from tkinter import *
from pygame import *
class firstscreen:
    def __init__(self):
        self.window = Tk()
        self.window.minsize(300, 250)
        self.window.resizable(width=False, height=False)
        self.window.title("Login")
        self.username = ""
        self.password = ""
        self.userlabel = Label(self.window, text="Username")
        self.userlabel.place(x=50, y=50)
        self.passlabel = Label(self.window, text="Password")
        self.passlabel.place(x=50, y=100)
        self.userentry = Entry(self.window, textvariable=self.username)
        self.userentry.place(x=110, y=50)
        self.passentry = Entry(self.window, textvariable=self.password, show="*")
        self.passentry.place(x=110, y=100)
        self.loginbutton = Button(self.window, text="Login", command = self.login())
        self.loginbutton.place(x=80, y=140)
        self.registerbutton = Button(self.window, text="Register",command=self.login())
        self.registerbutton.place(x=140, y=140)
        self.window.mainloop()
    def login(self):
        print("Hello")

class gamewindow():
    def __init__(self):
        pygame.init()
        game = pygame.display.set_mode((800, 300))
runlogin = firstscreen()
rungame = gamewindow()
NameError:name 'pygame' is not defined

(For line 29, pygame.init() )

like image 550
Commander Red Avatar asked Mar 02 '26 10:03

Commander Red


1 Answers

It has to be either

from pygame import *

# [...]

class gamewindow():
    def __init__(self):
        init()
        game = display.set_mode((800, 300))

or

import pygame

# [...]

class gamewindow():
    def __init__(self):
        pygame.init()
        game = pygame.display.set_mode((800, 300))

See The import system - Submodules

like image 145
Rabbid76 Avatar answered Mar 03 '26 22:03

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!