I have determined that in a Python TkInter GUI program, it is best practice to enclose the entire thing in a try / except block in order to catch all exceptions and present them to the end user (as opposed to something going wrong silently or the program exiting for seemingly no reason).
However, this approach has some problems. Consider the following tiny program that attempts to divide by 0 when a button is clicked:
import tkinter
class Foo():
def __init__(self):
# Initialize a new GUI window
root = tkinter.Tk()
# The "Generic error" message is shown when the following is uncommented
#number = 1 / 0
# Define a button and draw it
button = tkinter.Button(root, text='Generate an error', command=self.generate_error)
button.pack()
# Loop forever
root.mainloop()
def generate_error(self):
# The "Generic error" message is not shown
number = 1 / 0
if __name__ == '__main__':
try:
# Run the Foo class
Foo()
except Exception as e:
print('Generic error:', str(e))
Why does the "Generic error" statement not apply to the button callback function?