簡體   English   中英

調用一個函數並多次調用

[英]Calling a function and having it call multiple times

我在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時,它都會調用它,但是到目前為止我已經調用了很多次(第一次調用,第二次按下按鈕調用兩次,等等)。 我覺得好像必須在play()中,但是我一生都找不到它。

編輯 Player類中添加的buy_ship函數

可能是因為每次調用buy_ship時都會將功能綁定到按鈕。 因此,第二次您致電buy_ship。 以前的綁定仍然存在。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM