有没有办法修复 while 循环不使用 time.sleep 更新 tkinter 标签?
Posted
技术标签:
【中文标题】有没有办法修复 while 循环不使用 time.sleep 更新 tkinter 标签?【英文标题】:Is there a way to fix while loop not updating tkinter label with time.sleep? 【发布时间】:2020-01-20 05:22:11 【问题描述】:我刚刚编写了一个使用 Tkinter 的二十一点游戏,代码的每个部分都可以正常工作,除了我按下 Stand 按钮的部分(dealer_hit 函数开始的地方)我希望庄家放下牌减一。
我使用 time.sleep 方法让我的循环等待几秒钟,然后每两秒钟重复一次
import time
def dealer_hit(): # The action when you hit the stand button
if player_score < 21 and player_score != 0: # If statement to make sure the person is using the button at the right time
while dealer_score < 17: # loop to make sure the dealer doesn't stop until his score is more than 17
current_score = dealer_score_update(new_Cards) # get the next card from the deck
print('got') # print log
dealer_result_text.set(current_score) # Update the label which contains points
print('set') # print log
tkinter.Label(dealer_cards_frame, image=next_card_image).pack(side='left') # Put the image in the specific frame of cards
print('image') # print log
time.sleep(2) # wait 2 seconds and do the loop again
final_comparison() # a function to compare the results after the I Have just written a blackjack game in which I use Tkinter, Every part of the code works fine except in the section where I press the Stand button (Where the dealer_hit function starts) I want the dealer to put down the cards one by one.
睡眠方法似乎工作正常,日志打印在正确的时间,但 tkinter 窗口似乎被冻结并且在函数完全完成之前不会做任何事情,我想知道这是否与command=
代码中的参数。
完整代码 = https://paste.pythondiscord.com/akodovuqed.py
【问题讨论】:
Program freezing during the execution of a function in Tkinter的可能重复 【参考方案1】:您的代码被阻塞。当您是 using time.sleep()
时,整个脚本进入休眠状态,包括 GUI。
您可能必须将 gui/window 和脚本分成线程,以便它们可以相互等待。
更多关于线程在这里:https://docs.python.org/3.5/library/threading.html
【讨论】:
以上是关于有没有办法修复 while 循环不使用 time.sleep 更新 tkinter 标签?的主要内容,如果未能解决你的问题,请参考以下文章