asynctkinter


Nameasynctkinter JSON
Version 0.4.3 PyPI version JSON
download
home_pagehttps://github.com/gottadiveintopython/asynctkinter
Summaryasync library for tkinter
upload_time2025-08-30 23:35:40
maintainerNone
docs_urlNone
authorNattōsai Mitō
requires_python<4.0.0,>=3.10.0
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 atk

async def what_you_want_to_do(clock, label):
    print('A')
    await clock.sleep(1)
    print('B')
    await atk.event(label, '<Button>')
    print('C')

atk.start(what_you_want_to_do(...))
```

## Installation

Pin the minor version.

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

## Usage

```python
import tkinter as tk
import asynctkinter as atk


async def main(*, clock: atk.Clock, root: tk.Tk):
    label = tk.Label(root, text='Hello', font=('', 80))
    label.pack()

    # waits for 2 seconds to elapse
    await clock.sleep(2)

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

    # waits for either 5 seconds to elapse or a label to be pressed.
    # i.e. waits at most 5 seconds for a label to be pressed
    tasks = await atk.wait_any(
        clock.sleep(5),
        atk.event(label, '<Button>'),
    )
    if tasks[0].finished:
        print("Timeout")
    else:
        event = tasks[1].result
        print(f"The label got pressed. (pos: {event.x}, {event.y})")

    # same as the above
    async with clock.move_on_after(5) as timeout_tracker:
        event = await atk.event(label, '<Button>')
        print(f"The label got pressed. (pos: {event.x}, {event.y})")
    if timeout_tracker.finished:
        print("Timeout")

    # waits for both 5 seconds to elapse and a label to be pressed.
    tasks = await atk.wait_all(
        clock.sleep(5),
        atk.event(label, '<Button>'),
    )

    # nests as you want.
    tasks = await ak.wait_all(
        atk.event(label, '<Button>'),
        atk.wait_any(
            clock.sleep(5),
            ...,
        ),
    )
    child_tasks = tasks[1].result


if __name__ == "__main__":
    atk.run(main)
```

### threading

Unlike `trio` and `asyncio`, `asynckivy` does not provide any I/O primitives.
Therefore, if you don’t want to implement your own, using threads may be the best way to perform I/O without blocking the main thread.

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

executer = ThreadPoolExecuter()

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

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

Unhandled exceptions (excluding `BaseException` that is not `Exception`) are propagated to the caller
so you can catch them like you do in synchronous code:

```python
import requests
import asynctkinter as atk

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


## Notes

- You may want to read the [asyncgui's documentation](https://asyncgui.github.io/asyncgui/) as it is the foundation of this library.
- You may want to read the [asyncgui_ext.clock's documentation](https://asyncgui.github.io/asyncgui-ext-clock/) as well.
- I, the author of this library, am 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.10.0",
    "maintainer_email": null,
    "keywords": "async, tkinter",
    "author": "Natt\u014dsai Mit\u014d",
    "author_email": "flow4re2c@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/70/a7/1a5d75f862a19b549b0090779ff2f3b958d7b5ec9fa11ef351ce161f80f4/asynctkinter-0.4.3.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 atk\n\nasync def what_you_want_to_do(clock, label):\n    print('A')\n    await clock.sleep(1)\n    print('B')\n    await atk.event(label, '<Button>')\n    print('C')\n\natk.start(what_you_want_to_do(...))\n```\n\n## Installation\n\nPin the minor version.\n\n```text\npoetry add asynctkinter@~0.4\npip install \"asynctkinter>=0.4,<0.5\"\n```\n\n## Usage\n\n```python\nimport tkinter as tk\nimport asynctkinter as atk\n\n\nasync def main(*, clock: atk.Clock, root: tk.Tk):\n    label = tk.Label(root, text='Hello', font=('', 80))\n    label.pack()\n\n    # waits for 2 seconds to elapse\n    await clock.sleep(2)\n\n    # waits for a label to be pressed\n    event = await atk.event(label, '<Button>')\n    print(f\"pos: {event.x}, {event.y}\")\n\n    # waits for either 5 seconds to elapse or a label to be pressed.\n    # i.e. waits at most 5 seconds for a label to be pressed\n    tasks = await atk.wait_any(\n        clock.sleep(5),\n        atk.event(label, '<Button>'),\n    )\n    if tasks[0].finished:\n        print(\"Timeout\")\n    else:\n        event = tasks[1].result\n        print(f\"The label got pressed. (pos: {event.x}, {event.y})\")\n\n    # same as the above\n    async with clock.move_on_after(5) as timeout_tracker:\n        event = await atk.event(label, '<Button>')\n        print(f\"The label got pressed. (pos: {event.x}, {event.y})\")\n    if timeout_tracker.finished:\n        print(\"Timeout\")\n\n    # waits for both 5 seconds to elapse and a label to be pressed.\n    tasks = await atk.wait_all(\n        clock.sleep(5),\n        atk.event(label, '<Button>'),\n    )\n\n    # nests as you want.\n    tasks = await ak.wait_all(\n        atk.event(label, '<Button>'),\n        atk.wait_any(\n            clock.sleep(5),\n            ...,\n        ),\n    )\n    child_tasks = tasks[1].result\n\n\nif __name__ == \"__main__\":\n    atk.run(main)\n```\n\n### threading\n\nUnlike `trio` and `asyncio`, `asynckivy` does not provide any I/O primitives.\nTherefore, if you don\u2019t want to implement your own, using threads may be the best way to perform I/O without blocking the main thread.\n\n```python\nfrom concurrent.futures import ThreadPoolExecuter\nimport asynctkinter as atk\n\nexecuter = ThreadPoolExecuter()\n\nasync def async_fn(clock: atk.Clock):\n    # create a new thread, run a function inside it, then\n    # wait for the completion of that thread\n    r = await atk.run_in_thread(clock, thread_blocking_operation)\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 atk.run_in_executer(clock, executer, thread_blocking_operation)\n    print(\"return value:\", r)\n```\n\nUnhandled exceptions (excluding `BaseException` that is not `Exception`) are propagated to the caller\nso you can catch them like you do in synchronous code:\n\n```python\nimport requests\nimport asynctkinter as atk\n\nasync def async_fn(clock: atk.Clock):\n    try:\n        r = await atk.run_in_thread(clock, lambda: requests.get('htt...', timeout=10), ...)\n    except requests.Timeout:\n        print(\"TIMEOUT!\")\n    else:\n        print('RECEIVED:', r)\n```\n\n\n## Notes\n\n- You may want to read the [asyncgui's documentation](https://asyncgui.github.io/asyncgui/) as it is the foundation of this library.\n- You may want to read the [asyncgui_ext.clock's documentation](https://asyncgui.github.io/asyncgui-ext-clock/) as well.\n- I, the author of this library, am 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.4.3",
    "project_urls": {
        "Homepage": "https://github.com/gottadiveintopython/asynctkinter",
        "Repository": "https://github.com/gottadiveintopython/asynctkinter"
    },
    "split_keywords": [
        "async",
        " tkinter"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ef894bce1b25862ae90676157f8ebeef315920ce66139c84e4f6c5c71417ebe0",
                "md5": "df18eeda0575916d36a8d5117a866e34",
                "sha256": "54971a72f5e2de04239e5909813c5ae7e24ea5f70af55a7b1a4b54146a346715"
            },
            "downloads": -1,
            "filename": "asynctkinter-0.4.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "df18eeda0575916d36a8d5117a866e34",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0.0,>=3.10.0",
            "size": 6109,
            "upload_time": "2025-08-30T23:35:37",
            "upload_time_iso_8601": "2025-08-30T23:35:37.536349Z",
            "url": "https://files.pythonhosted.org/packages/ef/89/4bce1b25862ae90676157f8ebeef315920ce66139c84e4f6c5c71417ebe0/asynctkinter-0.4.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "70a71a5d75f862a19b549b0090779ff2f3b958d7b5ec9fa11ef351ce161f80f4",
                "md5": "48d833c307e7fbda970fc36eb27318a7",
                "sha256": "22c729fda44846a7bb494108916796cfc2861dcec6d51ab91b42f5afa6367c8c"
            },
            "downloads": -1,
            "filename": "asynctkinter-0.4.3.tar.gz",
            "has_sig": false,
            "md5_digest": "48d833c307e7fbda970fc36eb27318a7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0.0,>=3.10.0",
            "size": 5246,
            "upload_time": "2025-08-30T23:35:40",
            "upload_time_iso_8601": "2025-08-30T23:35:40.454764Z",
            "url": "https://files.pythonhosted.org/packages/70/a7/1a5d75f862a19b549b0090779ff2f3b958d7b5ec9fa11ef351ce161f80f4/asynctkinter-0.4.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-30 23:35:40",
    "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: 2.23507s