2014-01-07 242 views
0

我在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功能的播放器類

+0

我們可以看到'buy_ship'函數嗎?我認爲它更可能是那個。 –

+0

它發生在buy_ship以上的功能,但肯定。 – Faller

回答

1

這可能是因爲你綁定到按鈕每次buy_ship被稱爲功能。所以第二次你叫buy_ship。以前的綁定仍然存在。

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

是的,這是問題所在。要麼只進行一次連接,要麼使用適當的關鍵字來確保單個連接。 – amicitas

+0

我會試試看,你是什麼意思「適當的關鍵字」 – Faller

+0

精美的作品。感謝您通過M4rtini和amicitas上網。 – Faller