Last active
August 15, 2023 17:13
-
-
Save rafrafek/8d5bfa5ea1aad3f2bfddb71c196e9499 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from tkinter import Tk | |
from tkinter.ttk import Button, Frame, Label | |
from typing import Callable, Literal | |
from urllib.request import urlopen | |
FetchDataType = dict[Literal["q"] | Literal["a"], str] | |
def parse_zen_data(data: bytes) -> FetchDataType: | |
return json.loads(data)[0] | |
def fetch_zen_quote( | |
url: str = "https://zenquotes.io/api/random", | |
parse: Callable[[bytes], FetchDataType] = parse_zen_data, | |
) -> FetchDataType: | |
with urlopen(url) as response: | |
data = response.read() | |
return parse(data) | |
class App(Tk): | |
def __init__( | |
self, fetch_quote: Callable[[], FetchDataType] = fetch_zen_quote | |
) -> None: | |
super().__init__() | |
self.fetch_quote = fetch_quote | |
self.title("Zen quotes") | |
self.resizable(width=False, height=False) | |
self._configure_widgets() | |
self._update_zen_quote() | |
def _configure_widgets(self) -> None: | |
frame = Frame(self, padding=16) | |
frame.grid() | |
self.quote_label = Label(frame, padding=6) | |
self.quote_label.grid(column=0, row=0, columnspan=2) | |
self.author_label = Label(frame, padding=6) | |
self.author_label.grid(column=0, row=1, sticky="w", columnspan=2, pady=(0, 6)) | |
Button(frame, text="New quote", command=self._update_zen_quote).grid( | |
column=0, row=2, sticky="w" | |
) | |
Button(frame, text="Quit", command=self.destroy).grid( | |
column=1, row=2, sticky="e" | |
) | |
def _update_zen_quote(self) -> None: | |
data = self.fetch_quote() | |
self.quote_label["text"] = data["q"] | |
self.author_label["text"] = f"Author: {data['a']}" | |
def run(self) -> None: | |
self.mainloop() | |
if __name__ == "__main__": | |
App().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment