diff --git a/Lib/test/test_tkinter/test_misc.py b/Lib/test/test_tkinter/test_misc.py index 706c680d3d1f52..3b6b75b4c637fc 100644 --- a/Lib/test/test_tkinter/test_misc.py +++ b/Lib/test/test_tkinter/test_misc.py @@ -6,6 +6,7 @@ import signal import sys import textwrap +import threading import time import unittest import weakref @@ -16,6 +17,7 @@ from test import support from test.support import import_helper from test.support import os_helper +from test.support import threading_helper from test.support.isolation import runInSubprocess from test.support.script_helper import assert_python_ok from test.test_tkinter.support import setUpModule # noqa: F401 @@ -979,6 +981,97 @@ def test_iterable_protocol(self): widget in widget +def tcl_is_threaded(): + return (tcl_version >= (9,) or + tkinter.Tcl().eval('info exists tcl_platform(threaded)') == '1') + + +@unittest.skipIf(sys.platform == 'darwin', + 'Tk only works in the main thread on macOS') +@unittest.skipUnless(tcl_is_threaded(), 'requires Tcl with thread support') +@threading_helper.requires_working_threading() +class MainloopThreadsTest(unittest.TestCase): + # gh-162647: The mainloop() of Tcl interpreters in different threads + # should not affect each other. + + def setUp(self): + # Tk objects created in other threads must not become the default + # root. + self.addCleanup(setattr, tkinter, '_support_default_root', + tkinter._support_default_root) + tkinter._support_default_root = False + self.roots = {} + self.results = [] + + def mainloop_thread(self, name, ticking=False): + # Return a thread which runs mainloop() of a new Tk. + def run(): + root = tkinter.Tk() + root.withdraw() + if ticking: + def tick(): + root.after(20, tick) + tick() + self.roots[name] = root + try: + root.mainloop() + self.results.append((name, None)) + except BaseException as e: + self.results.append((name, e)) + finally: + # The interpreter should be deleted in its thread. + del self.roots[name] + root.destroy() + del root + _tkinter._finalize_thread() + return threading.Thread(target=run) + + def wait_mainloop(self, name): + for _ in support.sleeping_retry(support.SHORT_TIMEOUT): + if name in self.roots: + break + # A call from other thread waits until mainloop() runs. + self.roots[name].tk.call('info', 'patchlevel') + + def quit_all(self): + for root in list(self.roots.values()): + root.quit() + + def test_quit(self): + threads = [self.mainloop_thread('a'), + self.mainloop_thread('b', ticking=True)] + with threading_helper.start_threads(threads, unlock=self.quit_all): + self.wait_mainloop('a') + self.wait_mainloop('b') + # quit() stops the mainloop() of its interpreter even if it + # waits for events, and does not stop other mainloop(). + self.roots['a'].quit() + threads[0].join(support.SHORT_TIMEOUT) + self.assertEqual(self.results, [('a', None)]) + self.assertEqual(self.results, [('a', None), ('b', None)]) + + def test_callback_error(self): + threads = [self.mainloop_thread('b', ticking=True)] + with threading_helper.start_threads(threads, unlock=self.quit_all): + self.wait_mainloop('b') + root = tkinter.Tk() + self.addCleanup(root.destroy) + root.withdraw() + def callback(): + raise ZeroDivisionError + root.tk.createcommand('callback', callback) + root.tk.call('after', 0, 'callback') + root.update() + # Let the mainloop() in other thread run for a while. + time.sleep(0.2) + # The error was not raised in other thread... + self.assertEqual(self.results, [('b', None)]) + # ...but by the next mainloop() in this thread. + root.after(100, root.quit) + with self.assertRaises(ZeroDivisionError): + root.mainloop() + + class TkTest(AbstractTkTest, unittest.TestCase): def test_readprofile(self): diff --git a/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst b/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst new file mode 100644 index 00000000000000..cf069c8985d871 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-25-21-00-00.gh-issue-162647.Qm4Tsx.rst @@ -0,0 +1,4 @@ +Fix :mod:`tkinter` when Tcl interpreters run :meth:`!mainloop` in different +threads. :meth:`!quit` no longer stops the main loop of other interpreter, +and stops the main loop even if it waits for events. An exception raised in +a callback is no longer raised by the main loop in other thread. diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c index 57a932c35be2cd..2e64c7ba81cb37 100644 --- a/Modules/_tkinter.c +++ b/Modules/_tkinter.c @@ -31,6 +31,7 @@ Copyright (C) 1994 Steen Lumholt. #endif #include "pycore_long.h" // _PyLong_IsNegative() +#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_INT_RELAXED() #include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8String #include // SIGINT @@ -382,6 +383,7 @@ typedef struct { int threaded; /* True if tcl_platform[threaded] */ Tcl_ThreadId thread_id; int dispatching; + int quitting; /* Set by quit() to stop mainloop() */ int event_hook; /* True if counted by EnableEventHook() */ PyObject *trace; /* We cannot include tclInt.h, as this is internal. @@ -433,9 +435,14 @@ check_tcl_appartment(TkappObject *app) /**** Error Handling ****/ static PyObject *Tkinter_TclError; -static int quitMainLoop = 0; -static int errorInCmd = 0; -static PyObject *excInCmd; + +/* An exception raised in a Python callback, which should be raised by the + event loop (mainloop() or the event hook) that called the callback. + Callbacks are only called in the thread of their Tcl interpreter, so it + is thread-local. */ +static Tcl_ThreadDataKey excInCmd_key; +#define excInCmd \ + (*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *))) static PyObject *Tkapp_UnicodeResult(TkappObject *); @@ -2664,8 +2671,7 @@ PythonCmd(ClientData clientData, Tcl_Interp *interp, goto done; error: - errorInCmd = 1; - excInCmd = PyErr_GetRaisedException(); + Py_XSETREF(excInCmd, PyErr_GetRaisedException()); done: LEAVE_PYTHON @@ -2903,8 +2909,7 @@ FileHandler(ClientData clientData, int mask) res = PyObject_CallFunction(func, "Oi", file, mask); if (res == NULL) { - errorInCmd = 1; - excInCmd = PyErr_GetRaisedException(); + Py_XSETREF(excInCmd, PyErr_GetRaisedException()); } Py_XDECREF(res); LEAVE_PYTHON @@ -3108,8 +3113,7 @@ TimerHandler(ClientData clientData) Py_DECREF(v); /* See Tktt_New() */ if (res == NULL) { - errorInCmd = 1; - excInCmd = PyErr_GetRaisedException(); + Py_XSETREF(excInCmd, PyErr_GetRaisedException()); } else Py_DECREF(res); @@ -3171,10 +3175,10 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold) CHECK_TCL_APPARTMENT(self); self->dispatching = 1; - quitMainLoop = 0; + FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0); while (Tk_GetNumMainWindows() > threshold && - !quitMainLoop && - !errorInCmd) + !FT_ATOMIC_LOAD_INT_RELAXED(self->quitting) && + excInCmd == NULL) { int result; @@ -3204,12 +3208,12 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold) break; } self->dispatching = 0; - quitMainLoop = 0; + FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0); - if (errorInCmd) { - errorInCmd = 0; - PyErr_SetRaisedException(excInCmd); + PyObject *exc = excInCmd; + if (exc != NULL) { excInCmd = NULL; + PyErr_SetRaisedException(exc); return NULL; } Py_RETURN_NONE; @@ -3239,11 +3243,32 @@ _tkinter_tkapp_dooneevent_impl(TkappObject *self, int flags) _tkinter.tkapp.quit [clinic start generated code]*/ +static int +QuitEventProc(Tcl_Event *evPtr, int flags) +{ + /* Nothing to do: the event only wakes up the event loop. */ + return 1; +} + static PyObject * _tkinter_tkapp_quit_impl(TkappObject *self) /*[clinic end generated code: output=7f21eeff481f754f input=e03020dc38aff23c]*/ { - quitMainLoop = 1; + FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 1); + if (self->threaded && self->dispatching && + self->thread_id != Tcl_GetCurrentThread()) + { + /* mainloop() is running in other thread and can wait for an event. + Send it an event, so that it checks the flag. */ + Tcl_Event *ev = (Tcl_Event *)attemptckalloc(sizeof(Tcl_Event)); + if (ev == NULL) { + return PyErr_NoMemory(); + } + memset(ev, 0, sizeof(Tcl_Event)); + ev->proc = QuitEventProc; + Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(self->thread_id); + } Py_RETURN_NONE; } @@ -3771,7 +3796,6 @@ EventHook(void) stdin_ready = 0; #endif PyEval_RestoreThread(tstate); - errorInCmd = 0; #ifdef MS_WINDOWS hStdin = GetStdHandle(STD_INPUT_HANDLE); type = GetFileType(hStdin); @@ -3829,10 +3853,10 @@ EventHook(void) instead of returning to the prompt: without readline there is no input waiting on stdin yet, so returning here would block in fgets until the user hits enter, freezing later callbacks. */ - if (errorInCmd) { - errorInCmd = 0; - PyErr_SetRaisedException(excInCmd); + PyObject *exc = excInCmd; + if (exc != NULL) { excInCmd = NULL; + PyErr_SetRaisedException(exc); PyErr_Print(); } if (result < 0) diff --git a/Tools/c-analyzer/cpython/globals-to-fix.tsv b/Tools/c-analyzer/cpython/globals-to-fix.tsv index cd1939df856c16..456170c3a60d63 100644 --- a/Tools/c-analyzer/cpython/globals-to-fix.tsv +++ b/Tools/c-analyzer/cpython/globals-to-fix.tsv @@ -396,9 +396,6 @@ Modules/xxmodule.c - ErrorObject - ## state Modules/_datetimemodule.c - _datetime_global_state - Modules/_tkinter.c - tcl_lock - -Modules/_tkinter.c - excInCmd - -Modules/_tkinter.c - valInCmd - -Modules/_tkinter.c - trbInCmd - Modules/socketmodule.c - netdb_lock - @@ -429,8 +426,6 @@ Modules/readline.c - libedit_history_start - Modules/_ctypes/malloc_closure.c - free_list - Modules/_curses_panel.c - lop - Modules/_ssl/debughelpers.c _PySSL_keylog_callback lock - -Modules/_tkinter.c - quitMainLoop - -Modules/_tkinter.c - errorInCmd - Modules/_tkinter.c - Tkinter_busywaitinterval - Modules/_tkinter.c - call_mutex - Modules/_tkinter.c - var_mutex - diff --git a/Tools/c-analyzer/cpython/ignored.tsv b/Tools/c-analyzer/cpython/ignored.tsv index bda6ce14e8bcd3..4b1039269377df 100644 --- a/Tools/c-analyzer/cpython/ignored.tsv +++ b/Tools/c-analyzer/cpython/ignored.tsv @@ -263,6 +263,7 @@ Modules/_struct.c - bigendian_table - Modules/_struct.c - lilendian_table - Modules/_struct.c - native_table - Modules/_tkinter.c - state_key - +Modules/_tkinter.c - excInCmd_key - Modules/_interpchannelsmodule.c - _channelid_end_recv - Modules/_interpchannelsmodule.c - _channelid_end_send - Modules/_zoneinfo.c - DAYS_BEFORE_MONTH -