javascriptpythonhtmlpywebview

Close PyWebView Window with HTML Button click


Info in advance:
There is a similar question dealing with the same issue.
However, this one doesn't work for me (or I just don't know enough to include it properly).
I have only recently started working with pywebview.

The goal:
I want to close the window / end the programme with a link (or button) in HTML.

The problem:
The code used does not work for me.
The function can be reached (the print statement fills up the console,
unfortunately I have no idea why), but the window is not closed.
I am just starting with pywebview, so I don't really know what to do.


Used pages for problem solving:
PyWebView Website
StackOverflow Question


The Code (Python & HTML):

import sys

import webview


class Api:

    def __init__(self):
        self._window = None

    def set_window(self, window):
        self._window = window

    def destroy(window):
        print('Destroying window..')
        window.destroy()
        print('Destroyed!')


if __name__ == '__main__':
    api = Api()
    window = webview.create_window('Blackjack', 'index.html', js_api=api, min_size=(1000, 800))
    webview.start()
<html>
    <body>
        <main>
            <div id="content">
                <a>
                    <div class="block" onclick="exit()">End</div>
                </a>
                <script>
                    function exit() { pywebview.api.destroy() }
                </script>
            </div>
        </main>
    </body>
</html>

Solution

  • In the meantime I have found a solution that closes the window and exits the program.
    However, I get an error, unfortunately I do not know why.

    The HTML / JS code is correct so far and needs no adjustment.

    In the Python script, only def destroy(self) must be specified instead of def destroy(window).


    Pretty simple actually, but still took me almost a month to solve.