python - GUI无法正常工作

标签 python image user-interface audio tkinter

我想建立一个30秒的倒计时时钟,就像在电视节目中那样。

但是,当我运行此代码时,声音会播放,并且GUI无法响应,因此没有时钟出现。

当我将两个部分(时钟或声音)之一放进去时,它们起作用了,但是当我将它们实现到1个程序中时,它就不起作用了。

import tkinter as tk
from winsound import *
import time
def count_down():
    # start with 2 minutes --> 120 seconds
    for t in range(30, -1, -1):
        # format as 2 digit integers, fills with zero to the left
        # divmod() gives minutes, seconds
        sf = "{:02d}:{:02d}".format(*divmod(t, 60))
        #print(sf)  # test
        time_str.set(sf)
        root.update()
        # delay one second
        time.sleep(1)
# create root/main window
root = tk.Tk()
time_str = tk.StringVar()
# create the time display label, give it a large font
# label auto-adjusts to the font
label_font = ('calibri', 40)
tk.Label(root, textvariable=time_str, font=label_font, bg='black', fg='blue', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
# create start and stop buttons
# pack() positions the buttons below the label
play = lambda: PlaySound('countdown_clock.wav', SND_FILENAME)
photo2=tk.PhotoImage(file="play button2.png")
tk.Button(root, image=photo2, bg='black', padx=2, pady=2, command=count_down and play).pack()
# stop simply exits root window
photo=tk.PhotoImage(file="stop button.png")
tk.Button(root, image=photo, bg='black', padx=2, pady=2, command=root.destroy).pack()

# start the GUI event loop
root.mainloop()

最佳答案

count_down and play将返回play;因此,单击按钮时不调用count_down

>>> a = 'a_truth_value'
>>> b = 'another_truth_value'
>>> a and b
'another_truth_value'

您需要对其进行调整以调用这两个函数:
tk.Button(root, text='play button2', padx=2, pady=2,
          command=lambda: (count_down(), play())).pack()

关于python - GUI无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34368854/

相关文章:

python - 从另一个 django 项目中与外部 django 项目交互

image - 如果图像大于文本框,如何调整图像大小。但如果小于文本框,则不会增加比例

java - 使用具有大数据的 ZXing 库生成条码时遇到问题

user-interface - Web GUI 与 native GUI

python - 识别列表中的连续数字组

python - Django Admin Million Data - 管理页面打开时间太长

javascript - 使用 Javascript 选择多个图像但将数据存储在不同的位置

python - 如何使用嵌入在 PyQt GUI 中的终端

C#方法等待用户点击

Python:关于数学和负幂的问题