Tkinter自定义Frame子类销毁时报destroy()缺少event参数的TypeError问题
TypeError: destroy() missing 1 required positional argument: 'event' in Tkinter Hey there, let's break down this issue you're hitting with your custom Frame subclass in Tkinter. That error is a classic sign of a mismatch between how you're using the destroy method and how Tkinter expects it to work.
What's Causing the Error?
From what you described, there are two most likely culprits:
- You incorrectly overrode the
destroymethod in your custom Frame class by adding aneventparameter, but the nativetkinter.Frame.destroy()doesn't accept any arguments. When Tkinter tries to call this method automatically during window cleanup (without passing anevent), it throws the missing argument error. - You bound the
destroymethod directly to an event (like a<Destroy>trigger). Tkinter always passes aneventobject to event callback functions, but the nativedestroy()method doesn't expect this extra parameter.
How to Fix It
Let's go through solutions for both scenarios:
Scenario 1: Overrode destroy with an extra event parameter
If your custom Frame code looks like this:
import tkinter as tk class MyCustomFrame(tk.Frame): def __init__(self, parent): super().__init__(parent) # Your frame setup code here def destroy(self, event): # Extra `event` parameter is the problem! # Your custom cleanup logic (e.g., stopping threads, saving data) super().destroy()
Fix it by removing the event parameter:
class MyCustomFrame(tk.Frame): def __init__(self, parent): super().__init__(parent) # Your frame setup code here def destroy(self): # Your custom cleanup logic super().destroy()
Scenario 2: Bound destroy directly to an event
If you have code like this (binding destroy to an event):
self.bind("<Destroy>", self.destroy)
Fix it by wrapping the destroy call in a function that accepts the event parameter:
Option 1: Use a dedicated callback method
class MyCustomFrame(tk.Frame): def __init__(self, parent): super().__init__(parent) self.bind("<Destroy>", self._on_destroy) def _on_destroy(self, event): # Optional: Add event-specific logic here if needed self.destroy() # Call the native destroy method without extra args
Option 2: Use a lambda shortcut
self.bind("<Destroy>", lambda event: self.destroy())
Testing the Fix
After making these changes, try calling root.destroy() again. It should now properly destroy both the main window and your custom Frame without errors, instead of only partially cleaning up the Frame.
内容的提问来源于stack exchange,提问作者Pontios

