首页 > 解决方案 > 单击“开始”按钮后程序未按预期运行

问题描述

程序运行良好,直到我在底部添加了“开始”按钮。程序似乎运行正常,只是计时器没有更新。我希望计数器在我的程序中单击“开始”按钮后立即开始倒计时。

我的代码:

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()

标签: pythonpython-3.xtkinter

解决方案


你有几件事要在这里纠正。

首先这两行:

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()

推荐阅读