python - Tkinter 按钮卡在负载上
问题描述
我创建了一个带有两个tkinter按钮Start和Next. Start启用计时器并且Next应该显示下一个随机生成的短语。
在tk
窗口中,每当我第一次按下Start时,它都会显示加载图标,这不会让我按下Next按钮。我究竟做错了什么?:(
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 大喊小费!
所以,
- 在 Python 中导入threading包
- 而不是只运行以下
timer()
命令Start:
button1.config (command=timer)
,
为按钮创建一个新线程,Start并在该线程内部运行该timer()
函数:
button1.config (command=threading.Thread(target=timer).start())
这应该使Start按钮独立运行,并行允许我们点击Next没有问题:)
感谢所有评论的人!
编辑:
要使timer()
功能仅在Start按下按钮时运行,只需删除此行:
button2[“状态”] = 活动
推荐阅读
- .net - Microsoft .NET Framework 4 已经是该操作系统的一部分。您无需安装 .NET Framework 4 可再发行组件
- python - 在插补方法之间进行选择
- opencv - 将 tf.keras vgg16 分类器从 .pb 转换为 pbtxt 以用于 opencv dnn 模块
- c++ - 为什么此代码与操作员错误不匹配?
- php - PHP结果如何传递ajax成功函数
- php - Laravel:重构控制器的 store() 和 update() 方法
- javascript - not firing event in jquery
- emacs - 如何在 Doom Emacs 中设置相对行号
- linux - 如何使用热点运行 .sh 文件
- javascript - SelectField 创建下拉菜单