Skip to content

tkinter mainloop state is shared between Tcl interpreters #162647

Backlog

Description

@serhiy-storchaka

The flag set by quit() and the error raised in a callback are stored in global variables in _tkinter.c (quitMainLoop, errorInCmd and excInCmd), not per interpreter. With several Tcl interpreters in different threads, they affect the wrong mainloop().

quit() called for one interpreter can stop the mainloop() of other interpreter:

import threading, time, tkinter

roots = {}
ready = threading.Barrier(3)

def run(name, busy):
    root = roots[name] = tkinter.Tk()
    if busy:
        def tick():
            root.after(20, tick)
        tick()
    ready.wait()
    root.mainloop()
    print(name, 'mainloop exited')

threading.Thread(target=run, args=('A', False), daemon=True).start()
threading.Thread(target=run, args=('B', True), daemon=True).start()
ready.wait()
time.sleep(0.5)
roots['A'].quit()   # stops the mainloop of B, not A
time.sleep(1)

An error in a Python callback of one interpreter can be raised in the mainloop() of other interpreter, in other thread:

import threading, time, tkinter

ready = threading.Barrier(2)

def run_a():
    root = tkinter.Tk()
    def bad():
        raise ZeroDivisionError('callback of A')
    root.tk.createcommand('bad', bad)
    root.tk.call('after', 300, 'bad')
    ready.wait()
    for i in range(100):
        root.update()
        time.sleep(0.01)

def run_b():
    root = tkinter.Tk()
    def tick():
        root.after(20, tick)
    tick()
    ready.wait()
    root.mainloop()   # raises ZeroDivisionError('callback of A')

threading.Thread(target=run_a).start()
threading.Thread(target=run_b).start()

The same is true for SystemExit raised in a usual tkinter callback, since it is passed through.

These variables should be stored in the interpreter object. Also, quit() only takes effect after the next event is processed, so if it is called from other thread while the interpreter is idle, mainloop() continues to wait for an event.

Linked PRs

Activity

  1. added
    type-bug
    3.14
    3.15
    3.16
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.143.153.16topic-tkintertype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions