调用一个函数并让它多次调用

时间:2014-01-07 16:16:40

标签: python python-3.x pyqt pyqt5

我在PyQt5中遇到一个问题,如果我的一些功能,它会调用它,但是我已经多次调用它了。我会尝试用相关的代码。

class MainWindow(QtWidgets.QMainWindow, UI.MainUI.Ui_MainWindow):
    """The Main Window where everything happens"""
    def __init__(self, parent=None):
        """Initializes  (Don't use partial as most of the variables
        aren't created yet)"""
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.btn_buy_ship.clicked.connect(
            lambda: self.game.current_player.buy_ship(self))

    def new_game(self):
        """Runs tha actual Game"""
        self.game = Game(self)
        self.game.play(self)

class Game(object):
    """The Game Class"""
    def __init__(self, window):
        """The Obvious"""
        self.window = window
        self.makeshitgo = True
        super(Game, self).__init__()

    def play(self, window):
        """starts the game"""
        while self.makeshitgo:
             for i in self.players:
                self.current_player = i
               if i.ship.name is None:
                    i.buy_ship(window)
                while self.myturn:
                    QtWidgets.qApp.processEvents()
                    self.current_player.update_cargo(window)
                    time.sleep(.05)
             self.turn += 1

class Player:
    def __init__(self, ship, port, name):
        """Starts the player off with 0 everything and 5000 deblunes"""
        self.name = name

    def buy_ship(self, window):
        """Stops execution until ok/cancel is pressed"""
        window.change_ship("NA", "Galleon")

        def purchase():
            """buys the ship and updates money"""  # needs sell old ship
            if self.money >= int(window.V_Price.text()):
                self.ship = Ship(window.H_Ship_Name.text())
                self.change_money("down", self.ship.cost, window)
                window.textBrowser.append(self.ship.name)
                window.to_shipyard()
            else:
                window.textBrowser.append("You can't afford that brokearse")

        def cancel_purchase():
            """If you don't want to make a purchase"""
            if self.ship.name is None:
                window.textBrowser.append("You need a ship")
            else:
                window.to_shipyard()

        window.stackedWidget.setCurrentIndex(4)
        window.btn_buy.clicked.connect(purchase)
        window.btn_back_to_SY.clicked.connect(cancel_purchase)

现在,每当我打电话给i.buy_ship时,它都会调用它,但是我已经多次调用它(第一次调用它,第二次按下它调用的按钮两次,等等)。我觉得好像它必须在游戏()但我不能为我的生活找到它。

编辑在玩家类

中添加了buy_ship函数

1 个答案:

答案 0 :(得分:1)

这可能是因为每次调用buy_ship时你都会将一个函数绑定到按钮上。所以你第二次打电话给buy_ship。以前的绑定仍在那里。

window.stackedWidget.setCurrentIndex(4)
window.btn_buy.clicked.connect(purchase)
window.btn_back_to_SY.clicked.connect(cancel_purchase)