Skip to content

_tkinter PythonCmd fails to acquire GIL #84256

Open

Description

@speleo3
mannequin
BPO 40075
Nosy @pfmoore, @tjguk, @zware, @serhiy-storchaka, @zooba, @speleo3, @E-Paine
PRs
  • bpo-40075: Use PyGILState_Ensure in _tkinter PythonCmd #19178
  • gh-84256: Fix _tkinter resuming null thread state #22453
  • Files
  • qt_tk_demo.py: Minimal example
  • simple_tk_demo.py: Minimal example with only stdlib
  • tstate_acquire.diff
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = None
    created_at = <Date 2020-03-26.12:16:09.801>
    labels = ['3.8', '3.10', 'expert-tkinter', '3.9', 'type-crash']
    title = '_tkinter PythonCmd fails to acquire GIL'
    updated_at = <Date 2020-09-29.17:45:58.334>
    user = 'https://github.com/speleo3'

    bugs.python.org fields:

    activity = <Date 2020-09-29.17:45:58.334>
    actor = 'speleo3'
    assignee = 'none'
    closed = False
    closed_date = None
    closer = None
    components = ['Tkinter']
    creation = <Date 2020-03-26.12:16:09.801>
    creator = 'speleo3'
    dependencies = []
    files = ['49002', '49349', '49350']
    hgrepos = []
    issue_num = 40075
    keywords = ['patch']
    message_count = 8.0
    messages = ['365064', '374567', '374587', '374602', '374608', '377672', '377675', '377676']
    nosy_count = 7.0
    nosy_names = ['paul.moore', 'tim.golden', 'zach.ware', 'serhiy.storchaka', 'steve.dower', 'speleo3', 'epaine']
    pr_nums = ['19178', '22453']
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = 'crash'
    url = 'https://bugs.python.org/issue40075'
    versions = ['Python 3.8', 'Python 3.9', 'Python 3.10']

    Linked PRs

    Activity

    1. speleo3 commented on Mar 26, 2020

      speleo3mannequin
      MannequinAuthor

      The attached demo application runs a Tkinter GUI and a PyQt GUI in the same thread. PyQt owns the main loop and keeps updating the Tkinter instance by calling update().

      On Windows, when binding a "<Configure>" event, resizing the Tk window will lead to a crash:

      Fatal Python error: PyEval_RestoreThread: NULL tstate
      
      Current thread 0x00001f1c (most recent call first):
        File "qt_tk_demo.py", line 50 in <module>
      

      This crash happens in _tkinter.c in PythonCmd inside the ENTER_PYTHON macro.

      The issue can be fixed by using PyGILState_Ensure and PyGILState_Release instead of the ENTER_PYTHON macro inside the PythonCmd function.

    2. added
      type-crash
      on Mar 26, 2020
    3. E-Paine commented on Jul 29, 2020

      E-Painemannequin
      Mannequin

      Sorry for taking so long to do something with this issue. Can you please explain *why* (mostly because I don't really have a clue) acquiring the GIL fixes this crash (I am not disputing that it does - I have compared the current 3.9 branch against yours and confirmed this). Also, can it be reproduced with just the stdlib (so we can write a unittest for this)? Is it an assumption in QT about the GIL rather than a problem with _tkinter?

    4. added
      3.8 (EOL)
      3.9 (EOL)
      3.10 (EOL)
      on Jul 29, 2020
    5. zooba commented on Jul 29, 2020

      @zooba
      Member

      At a glance, it looks like ENTER_PYTHON will *restore* the GIL on the current thread, but it may be coming in on a thread that's never seen the GIL before.

      "The GIL" is actually the Python thread state, which is actually a per-thread data structure that's either active/locked or inactive/unlocked. If the current thread doesn't have a thread state, PyGILState_Ensure will create one, while ENTER_PYTHON will not.

      So the underlying issue is probably that the callbacks are coming in from a thread that they shouldn't be, and really ought to be marshalled back into the correct event loop first.

    6. speleo3 commented on Jul 30, 2020

      speleo3mannequin
      MannequinAuthor

      Attaching an even simpler example which doesn't use PyQt. It shows a native Windows dialog using ctypes. I could not reproduce the crash without showing any non-tk dialog.

      Steve's explanation sounds plausible.

    7. E-Paine commented on Jul 30, 2020

      E-Painemannequin
      Mannequin

      Thanks Steve for your explanation. I had a quick experiment with the ENTER_PYTHON definition and initially just added a call to PyThreadState_Get if the tstate was NULL. This still crashed the interpreter with the following error (which I think reaffirms Steve's explanation):

      Fatal Python error: PyThreadState_Get: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL)

      To work-around this error, I temporarily acquired the GIL and then released it after the call to PyThreadState_Get. The result worked correctly and can be found in the attached diff. I am not saying that the attached diff is the solution, but I don't think we need to stop using tstate in favour of the gstate introduced in the PR.

      I could not reproduce the crash without showing any non-tk dialog.

      That would help explain why I cannot reproduce it on Linux - it is differences in the windowing API under Tcl not some platform-specific code in Tcl/Tk or _tkinter.

    8. speleo3 commented on Sep 29, 2020

      speleo3mannequin
      MannequinAuthor

      I finally managed to test tstate_acquire.diff and it works perfectly! Should I close my pull request? Or update it with your patch?

    9. E-Paine commented on Sep 29, 2020

      E-Painemannequin
      Mannequin

      I do think we should close the existing PR (TBH, I completely forgot about this issue). Briefly looking again at the issue, it does indeed look like the GIL hasn't seen the thread before the attempted call to restore the tstate (as Steve said). If its alright with you, Thomas, I will open a new PR with the attached patch so it can be formally reviewed (though you can open the PR if you would prefer).

    10. speleo3 commented on Sep 29, 2020

      speleo3mannequin
      MannequinAuthor

      All good, thanks for opening PR 22453! I'll close my old PR.

    11. transferred this issue fromon Apr 10, 2022
    12. mdehoon commented on Apr 27, 2026

      @mdehoon
      Contributor

      As described in #22453 , this bug appears because we are entering an ENTER_PYTHON ... LEAVE_PYTHON block outside of a ENTER_TCL ... LEAVE_TCL block.
      You can avoid the bug, on Windows at least, by running tkinter's event loop (using tkroot.mainloop()) instead of Qt's event loop (using qtapp.exec_()), as follows:

      import sys
      
      # Hello-World with PyQt
      from PyQt5 import QtWidgets, QtCore
      qtapp = QtWidgets.QApplication(sys.argv)
      qtwindow = QtWidgets.QWidget()
      qtbutton = QtWidgets.QPushButton("Hello Qt", qtwindow)
      qtbutton.pressed.connect(lambda: QtWidgets.QMessageBox.information(qtwindow, "Test Qt", "Qt Button was pressed"))
      qtwindow.show()
      
      # Hello-World with Tkinter
      import tkinter
      from tkinter import messagebox
      tkroot = tkinter.Tk()
      tkroot.withdraw()
      tkwindow = tkinter.Toplevel(tkroot)
      tkinter.Button(tkwindow, text="Hello Tk", command=lambda: messagebox.showinfo("Test Tk", "Tk Button was pressed")).pack()
      
      # Bind the tkwindow <Configure> event
      def on_tk_configure(event):
          print(event)
          color = '#{:02x}{:02x}{:02x}'.format(event.width % 0xFF, event.height % 0xFF, event.x % 0xFF)
          tkwindow.config(bg=color)
      
      tkwindow.bind("<Configure>", on_tk_configure)
      
      sys.exit(tkroot.mainloop())

      which will ensure that you are always in an ENTER_TCL ... LEAVE_TCL block.

      This solution won't work on Unix. The code won't crash, but you would need to set up an external event loop to get both tkinter and qt events handled.

    13. added a commit that references this issue on Nov 24, 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.10 (EOL)3.8 (EOL)3.9 (EOL)topic-tkintertype-crash

      Projects

      No projects

        Milestone

        No milestone

        Relationships

        None yet

        Development

        No branches or pull requests

        Issue actions