【问题标题】:time clock with buttons in pythonpython中带有按钮的时钟
【发布时间】:2020-07-14 03:46:39
【问题描述】:

我正在尝试编写一个小时钟来跟踪我的工作时间。它是一个非常简单的程序,可以计算两个日期时间变量的差异。

我有以下问题:
当我按下停止按钮时,程序会打印正确的时间。但我想打印正确的时间然后重置计时器。但这不起作用,因为我无法更改变量“startzeit”。有什么办法可以让这个工作像真正的手表一样?

from tkinter import *
import datetime

startzeit = datetime.datetime.today()
stoppzeit = datetime.datetime.today()
date = datetime.date.today()


def start():
    global startzeit
    startzeit = datetime.datetime.today()


def stopp():
        stoppzeit = datetime.datetime.today()
        diff = stoppzeit-startzeit
        print(date, ":", diff)


fenster = Tk()
fenster.title("Stechuhr ")
fenster.geometry("170x40")

Start = Button(fenster, text="Start", command=start)
Start.place(x=10, y=10, width=70, height=20)

Stop = Button(fenster, text="Stop", command=stopp)
Stop.place(x=90, y=10, width=70, height=20)

mainloop()

【问题讨论】:

  • 1) 全局stoppzeit 不是必须的; 2) 添加global startzeit 并在stopp() 内的print(...) 之后为其分配stoppzeit 的值。

标签: python button tkinter stopwatch


【解决方案1】:

它已经对我有用了。但你可以做的是:

from tkinter import *
import datetime

global startzeit

startzeit = datetime.datetime.today()
stoppzeit = datetime.datetime.today()
date = datetime.date.today()


def start():
    global startzeit
    startzeit = datetime.datetime.today()


def stopp():
        global startzeit
        stoppzeit = datetime.datetime.today()
        diff = stoppzeit-startzeit
        diff = date ,":",diff
        label2.config(text=diff)
        print(diff)
        startzeit = stoppzeit


fenster = Tk()
fenster.title("Stechuhr ")
fenster.geometry("210x80")

label1 = Label(text="Zeit", padx=10, pady=5)
label1.place(x=10, y=5, width=70, height=20)

label2 = Label(text="Timediff", padx=10, pady=5)
label2.place(x=10, y=25, width=190, height=20)

Start = Button(fenster, text="Start", command=start)
Start.place(x=10, y=45, width=70, height=20)

Stop = Button(fenster, text="Stop", command=stopp)
Stop.place(x=90, y=45, width=70, height=20)

mainloop()

我所做的是:我在开头和每个使用全局声明的函数中都做了全局声明。这是告诉函数它应该使用变量 startzeit 的全局版本。

编辑: 我添加了startzeit = stoppzeit 和其他内容以在窗口中查看结果。 (抱歉无法评论atm)

【讨论】:

  • 但是你的代码没有在stopp()里面重置startzeit
  • @acw1668 但我们不需要,因为start() 覆盖了变量,因为全局声明,stopp() 不再使用局部变量。
  • 您好,感谢您的回答!有没有办法说:如果第二次按下停止它会打印:0
  • @Hank 该代码对您有用吗?对于您的第二个问题,是的,有:制作一个全球计数器。如果按下 stop 则让它向上计数,并在计数超过 1 时打印 0 的 if 情况。并在 start 函数中重置计数器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2013-04-19
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 2015-07-03
  • 2013-03-11
相关资源
最近更新 更多