我是Python的新手。我试图在单击按钮时更改按钮上的图像,并且我希望在执行任何其他代码之前渲染新图像。我尝试使用锁和信号量等,但没有任何工作(例如,下面的代码中的do_pause函数似乎在渲染图像之前执行)。我试图使用一个单独的线程,但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 :(得分: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