Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Last active May 3, 2021 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sourceperl/6b8e5a8efaecd122cccdc5319d2d87b1 to your computer and use it in GitHub Desktop.
Save sourceperl/6b8e5a8efaecd122cccdc5319d2d87b1 to your computer and use it in GitHub Desktop.
Display an auto-refresh webcam image (PNG) in a tkinter app
from datetime import datetime
import io
import sys
import urllib.request
import tkinter as tk
# sudo apt install python3-pil python3-pil.imagetk
import PIL.Image
import PIL.ImageTk
# some consts
IMG_URL = 'https://www.infoclimat.fr/cartes/getProxyWebcam.php?idw=274&c=30&t=png&70610'
# build tk interface
class MainApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# img container
self.lbl_img = tk.Label()
self.lbl_img.pack()
# start auto-refresh
self.update_img()
def update_img(self):
# log update
print('%s: update now' % datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
# do web request
try:
with urllib.request.urlopen(IMG_URL, timeout=10) as u:
raw_data = u.read()
# convert bytes RAW PNG data to Pillow (PIL) image and resize it
pil_img = PIL.Image.open(io.BytesIO(raw_data))
pil_img.thumbnail([1280, 720])
# convert PIL image to Tk format
tk_img = PIL.ImageTk.PhotoImage(pil_img)
self.lbl_img.configure(image=tk_img)
# don't remove: keep a ref to avoid del by garbage collect
self.lbl_img.tk_img=tk_img
except Exception as err:
print(err, file=sys.stderr)
# redo after 30s
self.after(30000, func=self.update_img)
if __name__ == '__main__':
app = MainApp()
app.title('Webcam Fort-Mahon-Plage')
app.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment