2015-12-22 59 views
0

我是Python新手。我试图在单击按钮时更改按钮上的图像,并且希望在执行任何其他代码之前呈现新图像。我尝试过使用锁和信号量等,没有任何工作(例如下面的代码中的do_pause函数似乎在呈现图像之前执行)。我试图使用单独的线程,但join()挂起了程序。这就像是在一个无限循环中,但我无法弄清楚为什么。python thread.join()挂起

# Game button click event 
def game_button_click(self, index): 
    self.clicks += 1 
    t1 = Thread(target=self.show_image, args=(index,)) 
    t1.start() 
    t1.join() 

    if self.clicks % 2 == 0 and self.uncovered % 2 == 0: 
     self.moves += 1 
     moves = self.MOVE_TEXT if self.moves == 1 else self.MOVES_TEXT 
     self.lbl_moves.config(text=str(self.moves) + moves) 
     if self.scrambled_names[self.prev_index] == self.scrambled_names[index]: 
      self.uncovered += 2 
     else: 
      self.do_pause() 
      self.buttons[self.prev_index].config(image=self.default_img, 
       command=lambda myIndex=self.prev_index: self.game_button_click(myIndex)) 
      self.buttons[index].config(image=self.default_img, 
       command=lambda myIndex=index: self.game_button_click(myIndex)) 
    self.prev_index = index 

# function to reveal the hidden image 
def show_image(self, index): 
    try: 
     new_img = Image.open(self.IMG_PATH + self.scrambled_names[index]) 
     self.game_images[index] = ImageTk.PhotoImage(new_img) 
     self.buttons[index].config(image=self.game_images[index], command=self.do_nothing) 
    except: 
     exception = sys.exc_info()[0] 
     print("Error: %s" % exception) 

# function to create pause 
def do_pause(self): 
    event = Event() 
    event.wait(timeout=self.PAUSE) 
+0

我忘了提及这些方法都在一个类内(所以也许这是一个范围问题)? – DanTheMan1966

+0

另外,使用IDLE,不知道是否有任何警告...... – DanTheMan1966

回答

0

想出了一个修复(不知道为什么它的工作原理)。我将game_button_click事件中的t1.join()之后的所有内容都移动到另一个名为check_for_match的方法。然后我改变了game_button_click事件中的代码。 do_pause和show_image代码几乎保持不变。就像我说的,不知道它为什么起作用,但它确实如此。这里是新的代码:

# Game button click event 
def game_button_click(self, index): 
    lock = Lock() 
    with lock: 
     self.show_image(index) 

    t = Thread(target=self.check_for_match, args=(index,)) 
    t.start() 

# function to check for matches 
def check_for_match(self, index): 
    self.clicks += 1 
    if self.clicks % 2 == 0 and self.uncovered % 2 == 0: 
     self.moves += 1 
     moves = self.MOVE_TEXT if self.moves == 1 else self.MOVES_TEXT 
     self.lbl_moves.config(text=str(self.moves) + moves) 
     if self.scrambled_names[self.prev_index] == self.scrambled_names[index]: 
      self.uncovered += 2 
     else: 
      self.do_pause() 
      self.buttons[self.prev_index].config(image=self.default_img, 
       command=lambda myIndex=self.prev_index: self.game_button_click(myIndex)) 
      self.buttons[index].config(image=self.default_img, 
       command=lambda myIndex=index: self.game_button_click(myIndex)) 
    self.prev_index = index