我想建立一个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/