From 5deb609663f426a8f38710a3156be6ba8b91d77d Mon Sep 17 00:00:00 2001 From: Martin Putzlocher Date: Wed, 1 Dec 2021 15:26:22 +0100 Subject: [PATCH] Stoppuhr --- tk_first_steps/stopwatch.py | 103 ++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 tk_first_steps/stopwatch.py diff --git a/tk_first_steps/stopwatch.py b/tk_first_steps/stopwatch.py new file mode 100644 index 0000000..9088cd9 --- /dev/null +++ b/tk_first_steps/stopwatch.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +from tkinter import * +from tkinter import ttk +from time import time + +# -------------------------- +# Model +# -------------------------- +class StopWatch: + def __init__(self): + self.seconds = 0.00 + self.starttime = 0.00 + self.running = False + + def switch(self): + if not self.running: + self.start() + else: + self.stop() + return self.running + + def start(self): + self.starttime = time() + self.running = True + + def stop(self): + self.seconds = time() - self.starttime + self.running = False + + def print_status(self): + if self.running: + print("Uhr läuft.") + else: + print("Uhr angehalten.") + + def get_time(self): + if not self.running: + return self.seconds + else: + return False + +# -------------------------- +# Controller +# -------------------------- +class WatchController: + def __init__(self, app): + self.app = app + self.sw = StopWatch() + + def switch_clock(self, event=None): + running = self.sw.switch() + if running: + stoppedtime = 0 + else: + stoppedtime = self.sw.get_time() + self.update_view(running, self.sw.get_time()) + + def update_view(self, running, stoppedtime): + self.app.update(running, stoppedtime) + +# -------------------------- +# View / Main Application +# -------------------------- +class StopWatch_App(Tk): + def __init__(self): + super().__init__() + self.controller = WatchController(self) + self.create_widgets() + self.bind_events() + + def create_control_variables(self): + self.btext = StringVar() + self.btext.set("Start") + self.etext = StringVar() + self.etext.set("0.00") + + def create_widgets(self): + mainframe = ttk.Frame(self, padding="3 3 3 3") + mainframe.grid(column=0, row=0, sticky=N+W+S+E) + self.columnconfigure(0, weight=1) + self.rowconfigure(0, weight=1) + self.button_switch = ttk.Button(mainframe, textvariable=self.btext, command=self.controller.switch_clock) + self.button_switch.grid(column=0, row=0, sticky=W) + self.entry_time = ttk.Entry(mainframe, state="readonly", textvariable=self.etext) + self.entry_time.grid(column=1, row=0, sticky=W) + + def bind_events(self): + self.bind("", self.controller.switch_clock) + + def update(self, running, stoppedtime): + if running: + self.btext.set("Stopp") + self.etext.set("running...") + else: + self.etext.set("{:2.3f}".format(stoppedtime)) + self.btext.set("Start") + +# -------------------------- +# Execution +# -------------------------- +if __name__ == "__main__": + app = StopWatch_App() + app.mainloop()