python - 单击“开始”按钮后程序未按预期运行
问题描述
程序运行良好,直到我在底部添加了“开始”按钮。程序似乎运行正常,只是计时器没有更新。我希望计数器在我的程序中单击“开始”按钮后立即开始倒计时。
我的代码:
import time
import tkinter as tk
def DisplayCountdown():
# Time
m = 0
s = 3
print('Running DisplayCountdown function')
if m == 0 and s == 0:
count_down_display.configure(text='Stand up!')
elif s == 0:
s=59
m-=1
count_down_display.after(1000, DisplayCountdown)
else:
s-=1
countdown_display.configure(text='%s minutes %s seconds' % (m,s))
countdown_display.after(1000, DisplayCountdown)
# Window
window = tk.Tk()
window.title('Stand Up Timer')
window.configure(bg = 'black')
# Information label
start_label = tk.Label(window,
font = 'ariel 40',
bg = 'black',
fg = 'red',
text = 'Click the start button to begin the timer.')
start_label.grid(row = 0, column = 0)
# Display Countdown
countdown_display = tk.Label(window,
font = 'ariel 40',
bg = 'black',
fg = 'red',
text = 'Countdown displayed here!')
countdown_display.grid(row = 1, column = 0)
# Start button
start_button = tk.Button(window,
text='Start',
command=DisplayCountdown)
start_button.grid(row = 2, column = 0)
# Window main loop
window.mainloop()
解决方案
你有几件事要在这里纠正。
首先这两行:
m = 0
s = 3
他们不能在这样的功能中。基本上每个循环总是从 am=0 s=3 开始。因此,请将它们作为参数传递给函数。
Next 更新您的命令和 after 语句以使用 lambda 传递初始和新时间变量。
接下来摆脱所有这些评论。它们是多余的。好的代码不需要注释,因为很明显发生了什么。对于可能需要为您自己或其他人解释的复杂代码部分,通常需要注释。
我不喜欢在小部件的每个参数之后都换行。就像你现在拥有的那样,它只是混乱的 IMO。我将所有内容都写在一行上,除非我们超出了 PEP8 推荐的行长,然后找到一个好地方去换行。
工作示例:
import tkinter as tk
def display_countdown(m, s):
print('Running DisplayCountdown function')
if m == 0 and s == 0:
countdown_display.configure(text='Stand up!')
elif s == 0:
s = 59
m -= 1
countdown_display.after(1000, lambda: display_countdown(m, s))
else:
s -= 1
countdown_display.configure(text='%s minutes %s seconds' % (m, s))
countdown_display.after(1000, lambda: display_countdown(m, s))
window = tk.Tk()
window.title('Stand Up Timer')
window.configure(bg='black')
start_label = tk.Label(window, font='ariel 40', bg='black', fg='red',
text='Click the start button to begin the timer.')
countdown_display = tk.Label(window, font='ariel 40', bg='black', fg='red',
text='Countdown displayed here!')
start_button = tk.Button(window, text='Start',
command=lambda: display_countdown(0, 3))
start_label.grid(row=0, column=0)
countdown_display.grid(row=1, column=0)
start_button.grid(row=2, column=0)
window.mainloop()
推荐阅读
- latex - svy后如何将表格输出到LaTeX:两种方式制表
- javascript - 在导致 oom 的大型数据集上解决 JSON.parse
- python - 有没有办法在python(Matplotlib)中设置y轴的限制?
- python - 如何在python游戏中显示宇航员
- javascript - 在 protobuf.js 中自动包装和解包 wrappers.proto 类型
- c# - Acumatica REST API 员工记录创建问题,适用于更新返回内部服务器错误 500
- python - DataFrame GroupBy 到 VolumeBars
- r - 埃拉托色尼筛的这个 R 函数是如何工作的?
- c++ - 复制构造函数 C++ 没有正确复制指针
- android - 如何延迟第二个片段,直到第一个在 ViewPager 中加载数据?