Skip to content

Commit b50b43d

Browse files
gh-162650: Fix tkinter calls from other threads after a nested mainloop() (GH-162651)
A nested mainloop() now restores the dispatching flag instead of resetting it, so the outer mainloop() still accepts calls from other threads. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b0b0005 commit b50b43d

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

‎Lib/test/test_tkinter/test_misc.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import signal
77
import sys
88
import textwrap
9+
import threading
910
import time
1011
import unittest
1112
import weakref
@@ -791,6 +792,31 @@ def callback(event):
791792
user32.SendMessageW(hwnd, WM_EXITSIZEMOVE, 0, 0)
792793
self.assertTrue(sizes)
793794

795+
def test_nested_mainloop(self):
796+
# gh-162650: Calls from other thread are still dispatched after
797+
# a nested mainloop() exits.
798+
root = self.root
799+
results = []
800+
def call():
801+
try:
802+
results.append(root.tk.call('expr', '6*7'))
803+
except RuntimeError as e:
804+
results.append(e)
805+
def start():
806+
root.after(0, root.quit)
807+
root.mainloop() # nested
808+
thread = threading.Thread(target=call)
809+
thread.start()
810+
def wait():
811+
if thread.is_alive():
812+
root.after(10, wait)
813+
else:
814+
root.quit()
815+
wait()
816+
root.after(0, start)
817+
root.mainloop()
818+
self.assertEqual(results, [42])
819+
794820
def test_wait_variable(self):
795821
var = tkinter.StringVar(self.root)
796822
self.assertEqual(self.root.waitvar, self.root.wait_variable)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :mod:`tkinter` calls from other threads failing with :exc:`RuntimeError`
2+
after a nested :meth:`!mainloop` exited, for example after
3+
:meth:`!SimpleDialog.go` returned.

‎Modules/_tkinter.c‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3169,6 +3169,9 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
31693169
PyThreadState *tstate = PyThreadState_Get();
31703170

31713171
CHECK_TCL_APPARTMENT(self);
3172+
/* mainloop() can be nested, the outer mainloop() still dispatches
3173+
events after the inner one exits. */
3174+
int dispatching = self->dispatching;
31723175
self->dispatching = 1;
31733176

31743177
quitMainLoop = 0;
@@ -3197,13 +3200,13 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
31973200
}
31983201

31993202
if (PyErr_CheckSignals() != 0) {
3200-
self->dispatching = 0;
3203+
self->dispatching = dispatching;
32013204
return NULL;
32023205
}
32033206
if (result < 0)
32043207
break;
32053208
}
3206-
self->dispatching = 0;
3209+
self->dispatching = dispatching;
32073210
quitMainLoop = 0;
32083211

32093212
if (errorInCmd) {

0 commit comments

Comments
 (0)