首页 > 解决方案 > Tkinter 按钮卡在负载上

问题描述

我创建了一个带有两个tkinter按钮StartNext. 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 ()

标签: pythontkinterbuttonloading

解决方案


好的修复它,不敢相信它是多么简单。向@TheLizzard 大喊小费!

所以,

  1. 在 Python 中导入threading包
  2. 而不是只运行以下timer()命令Start

button1.config (command=timer),

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

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

这应该使Start按钮独立运行,并行允许我们点击Next没有问题:)

感谢所有评论的人!

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

button2[“状态”] = 活动


推荐阅读