2016-09-15 119 views
0

我有一個程序使用pyqt的.animateClick()功能向用戶顯示用戶必須按特定順序複製的不同按鈕點擊順序。問題是我不想讓animateClick()發送一個信號,我只想要按鈕點擊來自用戶的信號。下面是我的一些代碼來演示我的意思,以及我如何解決這個問題(這不起作用)。我簡化了我的代碼,所以它更易於閱讀,如果您有任何問題,請告訴我。在PyQt中阻止按鈕點擊信號

from PyQt4 import QtCore,QtGui 
global flag 
global ai_states 
ai_states = [] 
user_states = [] 


class Program(object): 
    # Set up the push buttons 
    #Code Here. 

    # Connect push buttons to function get_state() 
    self.pushButton.clicked.connect(self.get_state) 
    self.pushButton_2.clicked.connect(self.get_state) 
    self.pushButton_3.clicked.connect(self.get_state)   
    self.pushButton_4.clicked.connect(self.get_state) 

    # Code that starts the start() function 

    def start(self): 
     flag = 0 
     ai_states[:] = [] 
     i = -1 
     # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers. 

     for k in ai_states: 
      i = i + 1 
      # Code here that animates button clicks determined by ai_states 

      # Changes the flag to 1 once the loop ends 
      if i == len(ai_states): 
       flag = 1 

    def get_state(self): 
     if flag == 1: 
      user_states.append(str(self.centralWidget.sender().text())) 
     else: 
      pass 

     if len(user_states) == len(ai_states): 
      # Checks to make sure the user inputted the same clicks as the ai_states 

即使該標誌在start()函數後出現1,它仍會附加animatedClick()信號。我究竟做錯了什麼?我是GUI編程的新手,所以我可能會以非常糟糕的方式解決這個問題。任何幫助,將不勝感激。

回答

1

永遠不要使用全局變量,除非你真的必須這樣做。如果您需要共享訪問變量,請使用實例屬性:

from PyQt4 import QtCore,QtGui 

class Program(object): 
    def __init__(self): 
     self.ai_states = [] 
     self.user_states = [] 
     self.flag = 1 

     # Set up the push buttons 
     # Code Here 

     # Connect push buttons to function get_state() 
     self.pushButton.clicked.connect(self.get_state) 
     self.pushButton_2.clicked.connect(self.get_state) 
     self.pushButton_3.clicked.connect(self.get_state)   
     self.pushButton_4.clicked.connect(self.get_state) 

    # Code that starts the start() function 

    def start(self): 
     self.flag = 0 
     del self.ai_states[:] 
     i = -1 
     # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers. 

     for k in self.ai_states: 
      i = i + 1 
      # Code here that animates button clicks determined by ai_states 

     # Changes the flag to 1 once the loop ends 
     self.flag = 1 

    def get_state(self): 
     if self.flag == 1: 
      self.user_states.append(str(self.centralWidget.sender().text())) 

     if len(self.user_states) == len(self.ai_states): 
      # Checks to make sure the user inputted the same clicks as the ai_states