Tkinter按钮卡在负载上



我创建了一个流行语游戏的版本,其中有两个tkinter按钮StartNextStart启用计时器,

Next在tk窗口中,每当我第一次按下开始时,它会显示加载图标,而我无法按下下一步

from tkinter import *
import random
from playsound import playsound
BEEPER = ('catchphrase.mp3', 'catchphrase_26_sec.mp3', 'catchphrase_15_sec.mp3')

# create window with button
root = Tk ()
root.geometry ('400x400')
# random word generator
with open ("Catchphrase-Words.txt", "r") as file:
allText = file.read ()
words = list (map (str, allText.splitlines ()))
# print random string
print (random.choice (words))

# define timer function:
def timer():
while playsound (random.choice (BEEPER)):
button2["state"] = ACTIVE

# define myClick function:
def gen_phrase():
label2.config (text=random.choice (words))

# create label
label = Label (root, text='''To earn points, make sure someone from your
team isn't caught holding the Catchphrase
game unit when the timer runs out!''', padx=50, pady=40)
label.pack ()
# create Start button
button1 = Button (root, text='Start', padx=10, pady=20)
button1.pack ()
button1.config (command=timer)
button1.config (font=('Ink Free', 20, 'bold'))
button1.config (activebackground='#fffb1f')
button1.config (fg='#50288C')
# Create Next button
button2 = Button (root, text='Next', padx=10, pady=20)
button2.pack ()
button2.config (command=gen_phrase)
button2.config (font=('Ink Free', 20, 'bold'))
button2.config (activebackground='#fffb1f')
button2.config (fg='#50288C')
# word generator in the window
label2 = Label (root, text=random.choice (words), padx=10, pady=10)
label2.config (font=('Monospace', 30, 'bold'))
label2.pack ()
root.mainloop ()

好的修复了它,真不敢相信它有多简单。大声向@TheLizzard索要小费!

所以,

  1. 在Python中导入线程
  2. 而不是仅在Start中运行timer()命令:

button1.config (command=timer)

Start按钮创建一个新线程,并在该线程内部运行timer()函数:

button1.config (command=threading.Thread(target=timer).start())

这将使开始按钮独立运行,同时允许我们毫无问题地单击

Next感谢所有发表评论的人!

编辑:要使timer()功能仅在按下开始按钮时运行,只需删除此行:

button2["state"]=活动

相关内容

  • 没有找到相关文章

最新更新