asynctkinter


Nameasynctkinter JSON
Version 0.3.1 PyPI version JSON
download
home_pagehttps://github.com/gottadiveintopython/asynctkinter
Summaryasync library for tkinter
upload_time2024-06-22 23:52:00
maintainerNone
docs_urlNone
authorNattōsai Mitō
requires_python<4.0.0,>=3.8.1
licenseMIT
keywords async tkinter
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AsyncTkinter

[Youtube](https://youtu.be/8XP1KgRd3jI)

`asynctkinter` is an async library that saves you from ugly callback-style code,
like most of async libraries do.
Let's say you want to do:

1. `print('A')`
1. wait for 1sec
1. `print('B')`
1. wait for a label to be pressed
1. `print('C')`

in that order.
Your code would look like this:

```python
def what_you_want_to_do(label):
    bind_id = None
    print('A')

    def one_sec_later(__):
        nonlocal bind_id
        print('B')
        bind_id = label.bind('<Button>', on_press, '+')
    label.after(1000, one_sec_later)

    def on_press(event):
        label.unbind('<Button>', bind_id)
        print('C')

what_you_want_to_do(...)
```

It's not easy to understand.
If you use `asynctkinter`, the code above will become:

```python
import asynctkinter as at

async def what_you_want_to_do(label):
    print('A')
    await at.sleep(label.after, 1000)
    print('B')
    await at.event(label, '<Button>')
    print('C')

at.start(what_you_want_to_do(...))
```

## Installation

Pin the minor version.

```text
poetry add asynctkinter@~0.3
pip install "asynctkinter>=0.3,<0.4"
```

## Usage

```python
from functools import partial
import tkinter as tk
import asynctkinter as at


def main():
    at.install()
    root = tk.Tk()
    at.start(async_main(root))
    root.mainloop()


async def async_main(root):
    sleep = partial(at.sleep, root.after)
    label = tk.Label(root, text='Hello', font=('', 80))
    label.pack()

    # wait for 2sec
    await sleep(2000)

    # wait for a label to be pressed
    event = await at.event(label, '<Button>')
    print(f"pos: {event.x}, {event.y}")

    # wait until EITHER a label is pressed OR 5sec passes.
    # i.e. wait at most 5 seconds for a label to be pressed.
    tasks = await at.wait_any(
        at.event(label, '<Button>'),
        sleep(5000),
    )
    if tasks[0].finished:
        event = tasks[0].result
        print(f"The label was pressed. (pos: {event.x}, {event.y})")
    else:
        print("5sec passed")

    # wait until a label is pressed AND 5sec passes.
    tasks = await at.wait_all(
        at.event(label, '<Button>'),
        sleep(5000),
    )


if __name__ == "__main__":
    main()
```

### threading

`asynctkinter` doesn't have any I/O primitives unlike Trio and asyncio do,
thus threads may be the best way to perform them without blocking the main thread:

```python
from concurrent.futures import ThreadPoolExecuter
import asynctkinter as at

executer = ThreadPoolExecuter()

async def async_fn(widget):
    # create a new thread, run a function inside it, then
    # wait for the completion of that thread
    r = await at.run_in_thread(thread_blocking_operation, after=widget.after)
    print("return value:", r)

    # run a function inside a ThreadPoolExecuter, and wait for its completion.
    # (ProcessPoolExecuter is not supported)
    r = await at.run_in_executer(executer, thread_blocking_operation, after=widget.after)
    print("return value:", r)
```

Exceptions(not BaseExceptions) are propagated to the caller,
so you can catch them like you do in synchronous code:

```python
import requests
import asynctkinter as at

async def async_fn(widget):
    try:
        r = await at.run_in_thread(lambda: requests.get('htt...', timeout=10), after=widget.after)
    except requests.Timeout:
        print("TIMEOUT!")
    else:
        print('RECEIVED:', r)
```


## Note

- You may want to read the [asyncgui's documentation](https://gottadiveintopython.github.io/asyncgui/) as it is the foundation of this library.
- I'm not even a tkinter user so there may be plenty of weird code in the repository.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/gottadiveintopython/asynctkinter",
    "name": "asynctkinter",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0.0,>=3.8.1",
    "maintainer_email": null,
    "keywords": "async, tkinter",
    "author": "Natt\u014dsai Mit\u014d",
    "author_email": "flow4re2c@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/a9/eb/9e17fdff0d5e269d7851292fa2a585a5809b2d95e77a868ae672fccd2f25/asynctkinter-0.3.1.tar.gz",
    "platform": null,
    "description": "# AsyncTkinter\n\n[Youtube](https://youtu.be/8XP1KgRd3jI)\n\n`asynctkinter` is an async library that saves you from ugly callback-style code,\nlike most of async libraries do.\nLet's say you want to do:\n\n1. `print('A')`\n1. wait for 1sec\n1. `print('B')`\n1. wait for a label to be pressed\n1. `print('C')`\n\nin that order.\nYour code would look like this:\n\n```python\ndef what_you_want_to_do(label):\n    bind_id = None\n    print('A')\n\n    def one_sec_later(__):\n        nonlocal bind_id\n        print('B')\n        bind_id = label.bind('<Button>', on_press, '+')\n    label.after(1000, one_sec_later)\n\n    def on_press(event):\n        label.unbind('<Button>', bind_id)\n        print('C')\n\nwhat_you_want_to_do(...)\n```\n\nIt's not easy to understand.\nIf you use `asynctkinter`, the code above will become:\n\n```python\nimport asynctkinter as at\n\nasync def what_you_want_to_do(label):\n    print('A')\n    await at.sleep(label.after, 1000)\n    print('B')\n    await at.event(label, '<Button>')\n    print('C')\n\nat.start(what_you_want_to_do(...))\n```\n\n## Installation\n\nPin the minor version.\n\n```text\npoetry add asynctkinter@~0.3\npip install \"asynctkinter>=0.3,<0.4\"\n```\n\n## Usage\n\n```python\nfrom functools import partial\nimport tkinter as tk\nimport asynctkinter as at\n\n\ndef main():\n    at.install()\n    root = tk.Tk()\n    at.start(async_main(root))\n    root.mainloop()\n\n\nasync def async_main(root):\n    sleep = partial(at.sleep, root.after)\n    label = tk.Label(root, text='Hello', font=('', 80))\n    label.pack()\n\n    # wait for 2sec\n    await sleep(2000)\n\n    # wait for a label to be pressed\n    event = await at.event(label, '<Button>')\n    print(f\"pos: {event.x}, {event.y}\")\n\n    # wait until EITHER a label is pressed OR 5sec passes.\n    # i.e. wait at most 5 seconds for a label to be pressed.\n    tasks = await at.wait_any(\n        at.event(label, '<Button>'),\n        sleep(5000),\n    )\n    if tasks[0].finished:\n        event = tasks[0].result\n        print(f\"The label was pressed. (pos: {event.x}, {event.y})\")\n    else:\n        print(\"5sec passed\")\n\n    # wait until a label is pressed AND 5sec passes.\n    tasks = await at.wait_all(\n        at.event(label, '<Button>'),\n        sleep(5000),\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### threading\n\n`asynctkinter` doesn't have any I/O primitives unlike Trio and asyncio do,\nthus threads may be the best way to perform them without blocking the main thread:\n\n```python\nfrom concurrent.futures import ThreadPoolExecuter\nimport asynctkinter as at\n\nexecuter = ThreadPoolExecuter()\n\nasync def async_fn(widget):\n    # create a new thread, run a function inside it, then\n    # wait for the completion of that thread\n    r = await at.run_in_thread(thread_blocking_operation, after=widget.after)\n    print(\"return value:\", r)\n\n    # run a function inside a ThreadPoolExecuter, and wait for its completion.\n    # (ProcessPoolExecuter is not supported)\n    r = await at.run_in_executer(executer, thread_blocking_operation, after=widget.after)\n    print(\"return value:\", r)\n```\n\nExceptions(not BaseExceptions) are propagated to the caller,\nso you can catch them like you do in synchronous code:\n\n```python\nimport requests\nimport asynctkinter as at\n\nasync def async_fn(widget):\n    try:\n        r = await at.run_in_thread(lambda: requests.get('htt...', timeout=10), after=widget.after)\n    except requests.Timeout:\n        print(\"TIMEOUT!\")\n    else:\n        print('RECEIVED:', r)\n```\n\n\n## Note\n\n- You may want to read the [asyncgui's documentation](https://gottadiveintopython.github.io/asyncgui/) as it is the foundation of this library.\n- I'm not even a tkinter user so there may be plenty of weird code in the repository.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "async library for tkinter",
    "version": "0.3.1",
    "project_urls": {
        "Homepage": "https://github.com/gottadiveintopython/asynctkinter",
        "Repository": "https://github.com/gottadiveintopython/asynctkinter"
    },
    "split_keywords": [
        "async",
        " tkinter"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "546081ded4272ee5858976a02b033800796ae9f4b4e8d54dc16c371f53576a7c",
                "md5": "3ec3bf12bd378cec1c6b1e18d7793044",
                "sha256": "5440128ae3a5fe3a183d439d60575e52cd385b961448bdb0803c775695b9a6f3"
            },
            "downloads": -1,
            "filename": "asynctkinter-0.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3ec3bf12bd378cec1c6b1e18d7793044",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0.0,>=3.8.1",
            "size": 4666,
            "upload_time": "2024-06-22T23:51:59",
            "upload_time_iso_8601": "2024-06-22T23:51:59.191087Z",
            "url": "https://files.pythonhosted.org/packages/54/60/81ded4272ee5858976a02b033800796ae9f4b4e8d54dc16c371f53576a7c/asynctkinter-0.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a9eb9e17fdff0d5e269d7851292fa2a585a5809b2d95e77a868ae672fccd2f25",
                "md5": "2c543b639e2a51c05f7fd00ef465bdc8",
                "sha256": "baf7c9b7e582287003de1a8a294bbfcf7b8856a53f4fd38d723a926b48d8d4be"
            },
            "downloads": -1,
            "filename": "asynctkinter-0.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "2c543b639e2a51c05f7fd00ef465bdc8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0.0,>=3.8.1",
            "size": 4119,
            "upload_time": "2024-06-22T23:52:00",
            "upload_time_iso_8601": "2024-06-22T23:52:00.984632Z",
            "url": "https://files.pythonhosted.org/packages/a9/eb/9e17fdff0d5e269d7851292fa2a585a5809b2d95e77a868ae672fccd2f25/asynctkinter-0.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-22 23:52:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "gottadiveintopython",
    "github_project": "asynctkinter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "asynctkinter"
}
        
Elapsed time: 0.24376s