Home Blog CV Projects Patterns Notes Book Colophon Search

Pystray

21 May, 2021

python3 -m venv venv
. venv/bin/activate
# On macOS you need the latest pip in order to get the pre-built pillow. Installing pillow from source fails due to a lack of libjpeg
pip install --upgrade pip
# Also install pillow and pyobjc dependencies
pip install pystray
import pystray
width = height = 512
color1 = '#c40'
color2 = '#049'

from PIL import Image, ImageDraw

def create_image():
    # Generate an image and draw a pattern
    image = Image.new('RGB', (width, height), color1)
    dc = ImageDraw.Draw(image)
    dc.rectangle(
        (width // 2, 0, width, height // 2),
        fill=color2)
    dc.rectangle(
        (0, height // 2, width // 2, height),
        fill=color2)

    return image



from pystray import Icon as icon, Menu as menu, MenuItem as item

state = False

def on_clicked(icon, item):
    global state
    state = not item.checked

from time import sleep
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret



def setup(icon):
    icon.visible = True
    print(state, icon)
    with make_server('', 8000, simple_app) as httpd:
        print("Serving on port 8000...")
        httpd.serve_forever()

import webbrowser
def on_click_me(*k, **p):
    print('Clicked', *k, **p)
    webbrowser.open('http://localhost:8000', new=0, autoraise=True)

# Update the state in `on_clicked` and return the new state in
# a `checked` callable
i = icon('test', create_image(), menu=menu(
    item(
        'Click me',
        on_click_me,
    ),
    item(
        'Checkable',
        on_clicked,
        checked=lambda item: state)))
print(i.HAS_NOTIFICATION)
i.run(setup=setup)
print('Never reached.')

Image

Comments

Be the first to comment.

Add Comment





Copyright James Gardner 1996-2020 All Rights Reserved. Admin.