Ga naar inhoud

tkinter

do_in_tkinter #

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

Gebruik deze function om een callback om te vormen naar een callback die uitgevoerd wordt in de thread waarin Tk uitgevoerd wordt. Dit om de "main thread is not in main loop" fouten die Tk kan geven te vermijden. Dit wordt gedaan door Tk periodiek te laten nakijken of er nieuwe data ontvangen is (door middel van 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) –

    je tk root object

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

    de callback functie die je wil laten uitvoeren op de tk thread

  • delay_in_ms (int, default: 10 ) –

    het interval waarop Tk nakijkt of er nieuwe data is

Returns (Callable[[Any], None]): een nieuwe callback functie die ervoor zorgt dat de gegeven callback functie laat uitvoeren op de 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