Skip to content

tkinter

do_in_tkinter #

do_in_tkinter(
    tk,
    callback: Callable[[Any], None],
    delay_in_ms: int = 10,
) -> Callable[[Any], None]

Use this function to convert a callback to a callback that runs in the thread in which Tk is executing. This is to avoid the "main thread is not in main loop" errors that Tk can raise. This will be done by having Tk periodically check whether new data has been received (using Tk.after(...))

Example:

microbit.buttons.on_button_a(press=do_in_tkinter(tk, pressed_callback_that_calls_tk))
microbit.accelerometer.notify(do_in_tkinter(tk, accelerometer_data_callback_that_calls_tk))

Parameters:

  • tk (Tk) –

    your tk root object

  • callback (Callable[[Any], None]) –

    the callback function you want to execute on the tk thread

  • delay_in_ms (int, default: 10 ) –

    the interval at which Tk checks for new data

Returns (Callable[[Any], None]): a new callback function that causes the given callback function to be executed on the Tk thread

Source code in src/kaspersmicrobit/tkinter.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def do_in_tkinter(tk, callback: Callable[[Any], None], delay_in_ms: int = 10) -> Callable[[Any], None]:
    """
    Use this function to convert a callback to a callback that runs in the thread in which Tk
    is executing. This is to avoid the "main thread is not in main loop" errors that Tk can raise. This will be
    done by having Tk periodically check whether new data has been received (using Tk.after(...))

    Example:
    ```python
    microbit.buttons.on_button_a(press=do_in_tkinter(tk, pressed_callback_that_calls_tk))
    microbit.accelerometer.notify(do_in_tkinter(tk, accelerometer_data_callback_that_calls_tk))
    ```

    Args:
        tk (Tk): your tk root object
        callback (Callable[[Any], None]): the callback function you want to execute on the tk thread
        delay_in_ms (int): the interval at which Tk checks for new data

    Returns (Callable[[Any], None]):
        a new callback function that causes the given callback function to be executed on the Tk thread
    """
    queue = _Queue()
    tk.after(delay_in_ms, lambda: _start_consuming_events(tk, queue, callback, delay_in_ms))
    return queue.append