python中带按钮的时钟

2024-10-06 06:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着编一个小时钟来跟踪我的工作时间。这是一个计算两个日期时间变量之差的非常简单的程序

我有以下问题:
当我按下停止按钮时,程序会打印正确的时间。但我想打印正确的时间,然后重置计时器。但这行不通,因为我无法更改变量“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()


Tags: import程序todaydatetimedatedef时间diff
1条回答
网友
1楼 · 发布于 2024-10-06 06:54:24

它已经对我起作用了。但你能做的是:

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)

相关问题 更多 >