diff --git a/Lib/test/test_tkinter/test_misc.py b/Lib/test/test_tkinter/test_misc.py index 5d78c6f9be04d93..3c53e4c7216b5d6 100644 --- a/Lib/test/test_tkinter/test_misc.py +++ b/Lib/test/test_tkinter/test_misc.py @@ -3,6 +3,7 @@ import signal import sys import textwrap +import threading import unittest import weakref import tkinter @@ -595,6 +596,31 @@ def callback(event): user32.SendMessageW(hwnd, WM_EXITSIZEMOVE, 0, 0) self.assertTrue(sizes) + def test_nested_mainloop(self): + # gh-162650: Calls from other thread are still dispatched after + # a nested mainloop() exits. + root = self.root + results = [] + def call(): + try: + results.append(root.tk.call('expr', '6*7')) + except RuntimeError as e: + results.append(e) + def start(): + root.after(0, root.quit) + root.mainloop() # nested + thread = threading.Thread(target=call) + thread.start() + def wait(): + if thread.is_alive(): + root.after(10, wait) + else: + root.quit() + wait() + root.after(0, start) + root.mainloop() + self.assertEqual(results, [42]) + def test_wait_variable(self): var = tkinter.StringVar(self.root) self.assertEqual(self.root.waitvar, self.root.wait_variable) diff --git a/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst b/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst new file mode 100644 index 000000000000000..0f4108e07b76a51 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-26-12-00-00.gh-issue-162650.Nm8Dsq.rst @@ -0,0 +1,3 @@ +Fix :mod:`tkinter` calls from other threads failing with :exc:`RuntimeError` +after a nested :meth:`!mainloop` exited, for example after +:meth:`!SimpleDialog.go` returned. diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c index a3f5162ce7e3043..8fff5ea92533899 100644 --- a/Modules/_tkinter.c +++ b/Modules/_tkinter.c @@ -3000,6 +3000,9 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold) PyThreadState *tstate = PyThreadState_Get(); CHECK_TCL_APPARTMENT(self); + /* mainloop() can be nested, the outer mainloop() still dispatches + events after the inner one exits. */ + int dispatching = self->dispatching; self->dispatching = 1; quitMainLoop = 0; @@ -3028,13 +3031,13 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold) } if (PyErr_CheckSignals() != 0) { - self->dispatching = 0; + self->dispatching = dispatching; return NULL; } if (result < 0) break; } - self->dispatching = 0; + self->dispatching = dispatching; quitMainLoop = 0; if (errorInCmd) {