If I run the following code from a terminal, I get a helpful error message in the terminal:
import Tkinter as tk
master = tk.Tk()
def callback():
raise
I found this thread while looking to solve the same problem. I had to make some modifications based on current tkinter
version methodologies. I also added a customized error message handler since I figured my user wouldn't know what the Tk error message meant.
In the __init__
of your class include:
parent.report_callback_exception = self.report_callback_exception
then in your Tk class:
def report_callback_exception(self, exc, val, tb):
#Handles tkinter exceptions
err_msg = {'Index 0 out of range': 'None found'}
try:
err = err_msg[str(val)]
except KeyError:
err = 'Oops, try again'
messagebox.showerror('Error Found', err)
You could expand the err_msg
dictionary to include whatever else you wanted. In my case I am building a searchable database off an Entry
object, so if the user has typed in a string that doesn't exist in the database, it is giving the user a plain language error.
First a followup: Just today, a patch on the CPython tracker for the tkinter.Tk.report_callback_exception
docstring made it clear that Jochen's solution is intended. The patch also (and primarily) stopped tk from crashing on callback exceptions when run under pythonw on Windows.
Second: here is a bare-bones beginning of a solution to making stderr
function with no console (this should really be a separate SO question).
import sys, tkinter
root = tkinter.Tk()
class Stderr(tkinter.Toplevel):
def __init__(self):
self.txt = tkinter.Text(root)
self.txt.pack()
def write(self, s):
self.txt.insert('insert', s)
sys.stderr = Stderr()
1/0 # traceback appears in window
More is needed to keep the popup window hidden until needed and then make it visible.
There is report_callback_exception
to do this:
import traceback
import tkMessageBox
# You would normally put that on the App class
def show_error(self, *args):
err = traceback.format_exception(*args)
tkMessageBox.showerror('Exception',err)
# but this works too
tk.Tk.report_callback_exception = show_error
If you didn't import 'Tkinter as tk', then do
Tkinter.Tk.report_callback_exception = show_error