在PythonPyGame中调用对象和传递变量无效错误表示变量未定义

2024-06-30 15:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

对于Python中对象和传递是如何工作的,我有点困惑。我想创建一个对象来调用类的函数,但我似乎无法让mainWindow变量通过。我一直收到一个错误,说主窗口尚未定义

几年前,我在TKinter中编写了一个程序,所有内容都在一个主方法中,在每个函数完成后,它将调用下一个函数并传递变量。我想看看是否可以通过对象调用函数来做同样的事情

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)

我想了解如何在类中调用函数,同时能够将变量和函数传递给所述函数


Tags: 对象函数selfinitdefdisplaypygame调用函数
1条回答
网友
1楼 · 发布于 2024-06-30 15:26:48

这里发生了几件事。首先,在__init__函数的作用域内定义mainWindow。这意味着不能从函数外部引用它。在开始将mainWindow传递到类的方法之前,您一直在正确使用OOP。相反,只需使用已经由__init__定义的mainWindow

您可以通过设置self.mainWindow来实现这一点self使属性对象特定

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()

相关问题 更多 >