为何tkinter与pynput组合在macOS上会导致Python崩溃?
macOS下pynput结合Tkinter导致Python崩溃的问题
问题背景
我正在开发一款基于CustomTkinter的Python宏功能应用,核心功能是通过pynput捕获按键。单独使用pynput捕获按键时功能正常,但下方的示例代码在Windows上运行无异常,在macOS上却会直接导致Python崩溃——涉及Intel和M2芯片、多个Python版本,以及Sonoma和Ventura系统。应用已获取macOS所需的辅助功能和输入监控权限。
触发崩溃的示例代码
import tkinter import threading from pynput import keyboard class KeyRecorder: def __init__(self) -> None: self.listener = None self.callback = None self.macro = [] def record(self, seconds, callback): self.callback = callback self.macro.clear() def on_press(key): self.macro.append(('press', key)) return True def on_release(key): self.macro.append(('release', key)) return True def end_recording(): self.listener.stop() self.callback(self.macro) self.listener = keyboard.Listener( on_press=on_press, on_release=on_release) self.listener.start() timer = threading.Timer(seconds, end_recording) timer.start() key_recorder = KeyRecorder() def record(): def handle_recording(keys): print(f"Callback called: {keys}") key_recorder.record(5, handle_recording) app = tkinter.Tk() button = tkinter.Button(command=record, text="Record") button.pack(pady=20) app.mainloop()
崩溃报告片段
Thread 8 Crashed: 0 libdispatch.dylib 0x18876fd0c _dispatch_assert_queue_fail + 120 1 libdispatch.dylib 0x18876fc94 dispatch_assert_queue + 196 2 HIToolbox 0x192f50b08 islGetInputSourceListWithAdditions + 160 3 HIToolbox 0x192f53144 isValidateInputSourceRef + 92 4 HIToolbox 0x192f53004 TSMGetInputSourceProperty + 44 5 libffi.dylib 0x1993ff050 ffi_call_SYSV + 80 6 libffi.dylib 0x199407adc ffi_call_int + 1208 7 _ctypes.cpython-312-darwin.so 0x104f5f3c8 _ctypes_callproc + 1384 8 _ctypes.cpython-312-darwin.so 0x104f572c4 PyCFuncPtr_call + 212 9 Python 0x1023f4ecc _PyObject_MakeTpCall + 128 10 Python 0x1025663f0 _PyEval_EvalFrameDefault + 47712 11 Python 0x1024179e8 gen_send_ex2 + 196 12 Python 0x102415cc8 gen_iternext + 36 13 Python 0x102557bcc builtin_next + 76 14 Python 0x102463774 cfunction_vectorcall_FASTCALL + 96 15 Python 0x10256628c _PyEval_EvalFrameDefault + 47356 16 Python 0x1023f8fdc method_vectorcall + 368 17 Python 0x102565b3c _PyEval_EvalFrameDefault + 45484 18 Python 0x1023f8fdc method_vectorcall + 368 19 Python 0x10267da84 thread_run + 92 20 Python 0x1025ef8fc pythread_wrapper + 48 21 libsystem_pthread.dylib 0x18891b034 _pthread_start + 136 22 libsystem_pthread.dylib 0x188915e3c thread_start + 8
疑问
我在pynput的GitHub仓库找到了相关问题报告,但未能完全理解;Stack Overflow上也存在类似未解答的问题。我清楚非Tkinter主线程更新UI元素会引发问题,但这段代码里并没有此类操作。想确认:是代码本身存在问题,只是在Windows上侥幸运行?还是遇到了pynput、macOS或Python的底层bug?
内容的提问来源于stack exchange,提问作者Jason Luther
相关产品推荐
相关产品推荐

