首页 > 解决方案 > 如何从python pyqt中的不同类调用函数

问题描述

请原谅我把事情复杂化了,事情就是这样发生的。所以我有这两个类,一个是windowm,另一个是modelm,我试图让它在调用newGame()时重新启动,所以这里有一些代码片段:

class windowm(QMainWindow):
    def __init__(self):
        super(windowm, self).__init__()

        # a generic widget for the center of the window
        widget = QWidget()
        self.setCentralWidget(widget)

和另一类:

class Model:
    def __init__(self):
        # setup is just starting a new game, so use that method
        self.newGame()

    def newGame(self):

        super(windowm, self).__init__()

是的,我知道这很复杂,请原谅我,这就是任务的方式。所以我明白,在我遇到这个烦人的独特场景之前,这个问题已经得到解答。正如您在第二个代码片段中看到的那样,我试图让它跳回“windowM”类并跳入函数init (self) 以重新启动游戏。请帮忙,谢谢!

标签: pythonqtpyqt5designer

解决方案


您必须创建另一个类的新实例,然后使用它来调用游戏函数。

我认为您会想要更改您的游戏类,因此从其他类开始新游戏会更容易。

class Model:
    def startNewGame(self):
        # setup is just starting a new game, so use that method
        self.newGame()

    def newGame(self):

        super(windowm, self).__init__()

然后可以这样使用:

class windowm(QMainWindow):
    def __init__(self):
        super(windowm, self).__init__()

        # a generic widget for the center of the window
        widget = QWidget()
        self.setCentralWidget(widget)
        # create an instance of the other class
        ng = Model()
        # start a new game
        ng.startNewGame()

推荐阅读