reddit-image-wall-getter/reddit_imgs/display_current_download.py

109 lines
3.3 KiB
Python

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import json
import tkinter
import traceback
from io import BytesIO
from pathlib import Path
from typing import Optional
from PIL import Image, ImageTk
millisamount = 10
AnyInt = Optional[int]
class MainApp(tkinter.Tk):
def __init__(self):
super().__init__()
self.geometry('500x500')
self.known_width = 500
self.known_height = 500
self.resizable(width=True, height=True)
self.photo = Image.new('RGB', (256, 256), (0, 0, 0))
self.display_photo = self.photo.copy()
self.image = ImageTk.PhotoImage(self.display_photo)
self.frame = tkinter.Frame(self)
self.frame.pack(fill=tkinter.BOTH, expand=tkinter.YES)
self.panel = tkinter.Label(self.frame)
self.panel.pack(fill=tkinter.BOTH, expand=tkinter.YES)
self.panel.bind('<Configure>', self._resize_image)
self.panel.configure(image=self.image)
self.update()
self._resize_image2()
self.update()
def _resize_image(self, event):
self.known_width = event.width
self.known_height = event.height
self._resize_image2()
def _resize_image2(self):
size_tuple = (self.known_width, self.known_height)
self.display_photo = self.photo.copy()
self.display_photo.thumbnail(size_tuple)
if self.display_photo is None:
self.display_photo = self.photo
self.image = ImageTk.PhotoImage(self.display_photo)
self.panel.configure(image=self.image)
def update_image(self, image, windowTile=None):
if windowTile is not None:
self.winfo_toplevel().title(str(windowTile))
self.photo = image
self._resize_image2()
self.update()
def updateImage(tk: MainApp, old_fpp_modified: AnyInt):
try:
file_path_path = Path('latest_image_download.txt')
new_fpp_modified = None
try:
st = file_path_path.stat()
new_fpp_modified = st.st_mtime_ns
except BaseException:
pass
tk.after(millisamount, updateImage, tk, new_fpp_modified)
if old_fpp_modified != new_fpp_modified:
file_path = None
info_path = None
file = None
info = None
try:
fpp = file_path_path.read_text()
file_path = Path(fpp)
info_path = Path(fpp+'.json')
file = file_path.read_bytes()
info = json.loads(info_path.read_text())
except BaseException:
pass
if file is not None and info is not None:
try:
tk.update_image(
Image.open(BytesIO(file)),
info.get('url', str(file_path).split('/', 1)[-1])
)
except BaseException:
print()
print("Exception on entry %r" % file_path)
traceback.print_exc()
if (old_fpp_modified is not None and new_fpp_modified is None):
tk.destroy()
except BaseException:
print()
traceback.print_exc()
tk.destroy()
def main():
tk = MainApp()
tk.after(1, updateImage, tk, None)
tk.mainloop()
if __name__ == '__main__':
main()