【问题标题】:how to call a function from a different class in python pyqt如何从python pyqt中的不同类调用函数
【发布时间】:2020-07-31 17:22:18
【问题描述】:

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

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

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

【问题讨论】:

  • 不确定我是否理解您的解释,但def newGame(self): windowm() 看起来就像您所需要的。另外,请尊重 Pyhon 的约定并将你的类名大写。
  • 是的,很抱歉有点匆忙
  • 所以它说没有定义 wondowm 是否需要其他东西?像我需要添加一些东西吗?或者可能是来自导入等的东西之一。

标签: python qt pyqt5 designer


【解决方案1】:

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

我想你会想要改变你的游戏类,所以从其他类开始新游戏会更容易。

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

【讨论】:

  • 所以我承认我是 python 新手,所以你知道在我的例子中我该怎么做吗??
  • 我对你的意思感到困惑
  • 我不确定你在哪里卡住了?我的示例代码是否返回了一些错误?
  • 它不知道什么是“windowm”
  • 这里是错误:self.dothis = windowm(QMainWindow) NameError: name 'windowm' is not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
相关资源
最近更新 更多