Title: Expose Tcl's external event loop API in tkinter · Issue #154801 · python/cpython · GitHub
Open Graph Title: Expose Tcl's external event loop API in tkinter · Issue #154801 · python/cpython
X Title: Expose Tcl's external event loop API in tkinter · Issue #154801 · python/cpython
Description: Feature or enhancement Proposal: Tkinter runs Tcl's event loop by calling Tcl_DoOneEvent repeatedly, which is the usual way of running the event loop in Tcl/Tk. This puts Tcl/Tk in charge of the event loop. Tcl also supports running exte...
Open Graph Description: Feature or enhancement Proposal: Tkinter runs Tcl's event loop by calling Tcl_DoOneEvent repeatedly, which is the usual way of running the event loop in Tcl/Tk. This puts Tcl/Tk in charge of the ev...
X Description: Feature or enhancement Proposal: Tkinter runs Tcl's event loop by calling Tcl_DoOneEvent repeatedly, which is the usual way of running the event loop in Tcl/Tk. This puts Tcl/Tk in charge of th...
Opengraph URL: https://github.com/python/cpython/issues/154801
X: @github
Domain: github.com
IPv4 address: 140.82.113.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Expose Tcl's external event loop API in tkinter","articleBody":"# Feature or enhancement\n\n### Proposal:\n\nTkinter runs Tcl's event loop by calling `Tcl_DoOneEvent` repeatedly, which is the usual way of running the event loop in Tcl/Tk. This puts Tcl/Tk in charge of the event loop.\n\nTcl also supports running external event loops via the function `Tcl_SetNotifier` and associated functions (`Tcl_QueueEvent` and `Tcl_ServiceAll` in particular). This part of Tcl's API is currently not exposed in tkinter. \n\nExposing `Tcl_SetNotifier` and associated functions would allow Tcl to use the event loop of a different GUI toolkit (e.g. Glib via pygobject) as an external event loop. Alternatively, a single event loop managed by Python can be used as an external event loop both by tkinter and other GUI toolkits at the same time.\n\nThis has two advantages:\n- It allows the use of multiple GUI toolkits at the same time, without the need for threads or polling (i.e., no busy-sleep loop, which is wasteful, slower, and fragile).\n- It makes threading easier, as it avoids the need for `ENTER_TCL` / `LEAVE_TCL` and `ENTER_PYTHON` / `LEAVE_PYTHON` (in the case of tkinter).\n\nBelow is a minimal script demonstrating how two GUI toolkits can run at the same time using a single event loop managed by Python (using `select` from the Python standard library, just to keep it simple).\n\n```python\nimport os\nimport select\nimport sys\nimport time\n\nimport tkinter\nfrom tkinter import _tkinter\n\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk, GLib\n\n\n# --- Create an event source for tkinter\n\nclass TkinterEventHandler:\n\n def __init__(self, callback):\n self.callback = callback\n self.ready_events = 0\n\n def process_event(self, flags):\n if not (flags & _tkinter.FILE_EVENTS):\n return False\n\n events = self.ready_events\n self.ready_events = 0\n if events != 0:\n self.callback(_tkinter.READABLE)\n\n return True\n\n def __call__(self, events):\n if self.ready_events == 0:\n _tkinter.queue_event(self.process_event)\n self.ready_events = events\n\n\nclass TkinterEventSource:\n\n def __init__(self):\n self.handlers = {}\n self.timer_abstime = 0\n\n def set_timer(self, interval_usec=None):\n mode = _tkinter.set_service_mode(_tkinter.SERVICE_ALL)\n if interval_usec is None:\n self.timer_abstime = 0\n else:\n now = time.perf_counter_ns() // 1000\n self.timer_abstime = now + interval_usec\n\n def wait_for_event(self, timeout):\n return 0\n\n def init_notifier(self):\n return\n\n def create_file_handler(self, fd, mask, callback):\n event_handler = TkinterEventHandler(callback)\n if mask & _tkinter.READABLE:\n self.handlers[fd] = event_handler\n\n def delete_file_handler(self, fd):\n try:\n del self.handlers[fd]\n except KeyError:\n pass\n\n def finalize_notifier(self, clientData):\n return\n\n def alert_notifier(self, clientData):\n return\n\n def service_mode_hook(self, mode):\n return\n \n def setup(self):\n timer_abstime = self.timer_abstime\n if timer_abstime > 0:\n now = time.perf_counter_ns() // 1000\n timeout_usec = timer_abstime - now\n if timeout_usec \u003c 0:\n timeout = 0\n else:\n timeout = timeout_usec / 1000000\n else:\n timeout = None\n fds = list(self.handlers.keys())\n return timeout, fds\n\n def check(self, ready_events):\n timer_abstime = self.timer_abstime\n result = 0;\n now = time.perf_counter_ns() // 1000\n if timer_abstime \u003c now:\n self.timer_abstime = 0\n ready_rlist, ready_wlist, ready_xlist = ready_events\n for fd in ready_rlist:\n handler = self.handlers.get(fd)\n if handler is None:\n continue\n handler(_tkinter.READABLE)\n _tkinter.service_all()\n\n# --- Tell Tcl to use TkinterEventSource as its notifier\n\ntkinter_event_source = TkinterEventSource()\n_tkinter.set_notifier(tkinter_event_source.set_timer,\n tkinter_event_source.wait_for_event,\n tkinter_event_source.create_file_handler,\n tkinter_event_source.delete_file_handler,\n tkinter_event_source.init_notifier,\n tkinter_event_source.finalize_notifier,\n tkinter_event_source.alert_notifier,\n tkinter_event_source.service_mode_hook\n )\n\n\n# --- Create an event source for GTK\n\nclass GTKEventSource:\n\n def setup(self):\n context = GLib.MainContext.default()\n if not context.acquire():\n raise RuntimeError(\"Failed to acquire the context\")\n ready, priority = context.prepare()\n timeout_msec, self.fds = context.query(priority)\n fds = [fd.fd for fd in self.fds]\n if timeout_msec == -1:\n timeout = None\n else:\n timeout = timeout_msec / 1000\n context.release()\n return timeout, fds\n\n def check(self, ready_events):\n context = GLib.MainContext.default()\n if not context.acquire():\n raise RuntimeError(\"Failed to acquire the context\")\n ready_rlist, ready_wlist, ready_xlist = ready_events\n ready_rlist = set(ready_rlist)\n for fd in self.fds:\n if fd.fd in ready_rlist:\n fd.revents |= GLib.IO_IN\n some_ready = context.check(GLib.MAXINT, self.fds)\n context.dispatch()\n context.release()\n\ngtk_event_source = GTKEventSource()\n\n\n# --- Make one example window for tkinter\n\nclass TkinterWindow:\n\n def __init__(self):\n self.window = tkinter.Tk()\n self.window.title(\"Tkinter\")\n\n self.button1 = tkinter.Button(self.window,\n text=\"Click me\",\n command=self.clicked,\n font='Helvetica 20',\n width=20,\n background='pale green')\n self.button1.pack()\n\n pipe_read_fd, self.pipe_write_fd = os.pipe()\n self.window.tk.createfilehandler(pipe_read_fd,\n tkinter.READABLE,\n self.read_from_pipe)\n self.button2 = tkinter.Button(self.window,\n text=\"Trigger the file descriptor\",\n command=self.write_to_pipe,\n font='Helvetica 20',\n width=20,\n background='lightblue')\n self.button2.pack()\n\n self.button3 = tkinter.Button(self.window,\n text=\"Start the timer (1 sec)\",\n command=self.update_timer,\n font='Helvetica 20',\n width=20,\n background='steelblue')\n self.button3.pack()\n\n def clicked(self):\n print(\"Tkinter button clicked\")\n\n def write_to_pipe(self):\n message = \"Tkinter file descriptor triggered\"\n n = os.write(self.pipe_write_fd, message.encode())\n\n def read_from_pipe(self, fd, mask):\n message = os.read(fd, 1024)\n print(message.decode())\n\n def update_timer(self, counter=0):\n print(\"Tkinter timer update %d\" % counter)\n self.window.after(1000, self.update_timer, counter+1)\n\ntkinter_window = TkinterWindow()\n\n# --- Make one example window for GTK\n\nsettings = Gtk.Settings.get_default()\nsettings.props.gtk_theme_name = \"Adwaita\"\n\nclass GTKWindow(Gtk.ApplicationWindow):\n\n def __init__(self, **kargs):\n super().__init__(**kargs, title='GTK')\n\n self.grid = Gtk.Grid()\n self.add(self.grid)\n\n button1 = self.create_button(1, text=\"Click me\", color=\"red\")\n button1.connect(\"clicked\", self.clicked)\n self.grid.attach(button1, 0, 0, 1, 1)\n\n pipe_read_fd, self.pipe_write_fd = os.pipe()\n GLib.io_add_watch(pipe_read_fd, GLib.IOCondition.IN, self.read_from_pipe)\n button2 = self.create_button(2, text=\"Trigger the file descriptor\", color='orchid')\n button2.connect(\"clicked\", self.write_to_pipe)\n self.grid.attach(button2, 0, 1, 1, 1)\n\n button3 = self.create_button(3, text=\"Start the timer (2 sec)\", color='salmon')\n button3.connect(\"clicked\", self.start_timer)\n self.grid.attach(button3, 0, 2, 1, 1)\n\n self.show_all()\n\n def create_button(self, number, text, color):\n button = Gtk.Button.new_with_label(text)\n key = \"custom-button%d\" % number\n button.get_style_context().add_class(key)\n css_provider = Gtk.CssProvider()\n css_provider.load_from_data(b\"\"\"\n .%s {\n font-family: Helvetica;\n font-size: 20pt;\n background: %s;\n color: black;\n }\n \"\"\" % (key.encode(), color.encode()))\n # Apply the CSS to the display\n style_context = button.get_style_context()\n style_context.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)\n style_context.add_class(key) # Add the CSS class to the button\n return button\n\n def clicked(self, button):\n print(\"GTK button clicked\")\n\n def write_to_pipe(self, button):\n message = \"GTK file descriptor triggered\"\n n = os.write(self.pipe_write_fd, message.encode())\n\n def read_from_pipe(self, fd, condition):\n if condition & GLib.IOCondition.IN:\n message = os.read(fd, 1024)\n print(message.decode())\n return True\n\n def update_timer(self):\n print(\"GTK timer update %d\" % self.counter)\n self.counter += 1\n return True\n\n def start_timer(self, button):\n self.counter = 0\n GLib.timeout_add(2000, self.update_timer)\n\n\nglib_window = GTKWindow()\n\n\n# --- run the event loop with the two GUI frameworks as event sources\n\nsources = [tkinter_event_source, gtk_event_source ]\n\n\nwhile True:\n rlist = []\n wlist = []\n xlist = []\n shortest_timeout = None\n for source in sources:\n timeout, fds = source.setup()\n if timeout is not None:\n if shortest_timeout is None:\n shortest_timeout = timeout\n else:\n if timeout \u003c shortest_timeout:\n shortest_timeout = timeout\n rlist.extend(fds)\n ready_events = select.select(rlist, wlist, xlist, shortest_timeout)\n for source in sources:\n source.check(ready_events)\n\n```\n\n\n### Has this already been discussed elsewhere?\n\nI have already discussed this feature proposal on Discourse\n\n### Links to previous discussion of this feature:\n\nhttps://discuss.python.org/t/connecting-asyncio-and-tkinter-event-loops/14722/40\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-155805\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/mdehoon","@type":"Person","name":"mdehoon"},"datePublished":"2026-07-28T06:55:03Z","url":"https://github.com/python/cpython/issues/154801"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:dde18727-934b-eb4d-abca-07d7d3d762fa |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E9AE:3690E2:E548DA:1330292:6B064E0F |
| html-safe-nonce | e580e4b6747e975d040c9abe3ccb71694adfc7f19c1157521df3d6bf87f55517 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFOUFFOjM2OTBFMjpFNTQ4REE6MTMzMDI5Mjo2QjA2NEUwRiIsInZpc2l0b3JfaWQiOiI3OTQzNDQyODA2Mjk4MDA1MDA3IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | b4e17e97b4a664e9f4f857b77fc0f605f380d187aed8415a882561001aa3ce04 |
| hovercard-subject-tag | issue:4995824771 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/154801/issue_layout |
| twitter:image | https://opengraph.githubassets.com/554bd08ea73f7f0b377709b852741d30cf7a722224f67f13595139d0135c2b79/python/cpython/issues/154801 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/554bd08ea73f7f0b377709b852741d30cf7a722224f67f13595139d0135c2b79/python/cpython/issues/154801 |
| og:image:alt | Feature or enhancement Proposal: Tkinter runs Tcl's event loop by calling Tcl_DoOneEvent repeatedly, which is the usual way of running the event loop in Tcl/Tk. This puts Tcl/Tk in charge of the ev... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | mdehoon |
| hostname | github.com |
| expected-hostname | github.com |
| None | 772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | f1f9a08f7c769a37f1dfc18ad43d463c222a7eea |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width