如何在第一个 Traceback 之前首先执行我的自定义错误消息?

How do I execute first my custom error message before the first Traceback?

我用 Tkinter 做了一个有限制的程序,我创建了一个自定义错误消息,其中如果满足限制条件,就会弹出一个错误消息框。

现在,我的问题是消息框只在我的程序终止后弹出,它没有得到 在程序仍处于打开状态时执行,这是我的代码。

try:
    None

except:
    raise SyntaxError(messagebox.showerror('Error', 'Error message')

这是输出:

Exception in Tkinter callback Traceback (most recent call last):
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\user1\PycharmProjects\Python Program\main.py", line 53, in command=lambda: equal(), relief=FLAT, borderwidth=1) File "C:\Users\user1\PycharmProjects\Python Porgram\main.py", line 32, in equal result = str(eval(expression)) File "", line 1 */ ^ SyntaxError: invalid syntax Traceback (most recent call last): File "C:\Users\user1\PycharmProjects\Python Program\main.py", line 171, in raise SyntaxError(messagebox.showerror('Error', 'You cannot bundle two or more operations together.')) SyntaxError: ok

进程已完成,退出代码为 1

try:
    # Anything you want to do.
    # If in this block a SyntaxError happens, you'll
    # catch it with the line below and do whatever you want
    # instead of raising and actual exception.
except SyntaxError:
    messagebox.showerror('Error', 'Error message')

如果您不知道在您的 try 中可以引发哪些类型的异常,您可以将 except SyntaxError: 替换为 except:。但我建议您在这里明确说明,但有例外。如有异常,请附加具体的。