Search code examples
pythonpywebview

Image display on pop up window


I am working on a windows desktop app using pywebview. I want to achieve a full image on the start up window for 5 secs. A very good example Easeus application on start up it shows an Image like this; enter image description here

These are my python codes;

import webview
import requests
import tkinter as tk

# initializing URL
url = "http:127.0.0.1:81"
timeout = 10
try:
# requesting URL
request = requests.get(url,
                       timeout=timeout)
webview.create_window('Hello', 'http://127.0.0.1:8000/', resizable=True)
webview.start()

# catching exception
except (requests.ConnectionError,
    requests.Timeout) as exception:
window = tk.Tk()
greeting = tk.Label(text="Hello, Tkinter")
greeting.pack()

Solution

  • In official documentation for pywebview I found example destroy window. It closes window after 5 seconds.

    import webview
    import time
    
    def destroy(window):
        # show the window for a few seconds before destroying it:
        time.sleep(5)
        print('Destroying window..')
        window.destroy()
        print('Destroyed!')
    
    if __name__ == '__main__':
        window = webview.create_window('Destroy Window Example', 'https://pywebview.flowrl.com/hello')
        webview.start(destroy, window)
        print('Window is destroyed')
    

    But if you use tkinter then you could use tk.Label(image=...) - and window.after(5000, window.destroy) to close window after 5000ms (5 seconds)

    import tkinter as tk
    
    window = tk.Tk()
    
    img = tk.PhotoImage(file='image.png')  # has to be `file=`
    
    tk.Label(image=img).pack()
    
    window.after(5000, window.destroy)     # `destroy` without `()`
    
    window.mainloop()
    

    For .jpg it may need PIL.ImageTk

    import tkinter as tk
    from PIL import ImageTk
    
    window = tk.Tk()
    
    img = ImageTk.PhotoImage(file='image.jpg')  # has to be `file=`
    
    tk.Label(image=img).pack()
    
    window.after(5000, window.destroy)     # `destroy` without `()`
    
    window.mainloop()
    

    EDIT:

    You can also use pywebview to display HTML with image, and with tag <meta http-equiv="refresh" content="5;https://..."> and it will redirect to other page after 5 second

    index.html

    <meta http-equiv="refresh" content="5;https://stackoverflow.com">
    
    <a href="https://en.wikipedia.org/wiki/Lenna">Lenna</a> from Wikipedia:<br>
    
    <img src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png">
    

    main.py

    import webview
    
    webview.create_window('Example', 'index.html')
    webview.start()
    

    And if you use this method then you don't need Python to start it.
    You can use bash/batch script with chrome.exe index.html