这是一个错误的示例代码:
from tkinter import Tk, messagebox
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
if messagebox.askyesno("Неизвестная ошибка", "Сохранить лог с ошибкой?") == True:
with open('error.txt', 'w', encoding='utf-8') as f:
f.write(text)
raise SystemExit
import sys
sys.excepthook = log_uncaught_exceptions
root = Tk()
def m_geometry(win):
#x = (win.winfo_screenwidth() / 2) - (295 / 2)
y = (win.winfo_screenheight() / 2) - (395 / 2)
root.wm_geometry("+%d+%d" % (x, y))
root.after(2000, lambda: m_geometry(root)) #Функция m_geometry(root) сработает через 2 секунды
root.mainloop()
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 746, in callit
func(*args)
File "C:/.../Error.py", line 27, in <lambda>
root.after(2000, lambda: m_geometry(root))
File "C:/.../Error.py", line 25, in m_geometry
root.wm_geometry("+%d+%d" % (x, y))
NameError: name 'x' is not defined
Process finished with exit code -1
必须有关于选择的消息:是否保存日志
钩子
sys.excepthook不起作用,因为它tkinter处理回调中的异常,并且为了能够自己处理这些异常,您需要使用root.report_callback_exception: