Informatik10/tk_first_steps/stopwatch.py

105 lines
2.9 KiB
Python
Raw Normal View History

2021-12-01 14:26:22 +00:00
#!/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_control_variables()
2021-12-01 14:26:22 +00:00
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("<Return>", 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()