在 python tkinter 中处理异常 [英] Handling exception in python tkinter

查看:44
本文介绍了在 python tkinter 中处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Python Tkinter 编写了一个应用程序.我最近注意到,对于其中一项操作,如果该操作失败,它有时会关闭(没有给出任何错误).我写了一个小程序来说明这个问题:-

I have written an application in Python Tkinter. I recently noticed that for one of the operation, it sometimes closes (without giving any error) if that operation failed. I have written a small program to illustrate the problem :-

import os
from Tkinter import *

def copydir():
    src = "D:\\a\\x\\y"
    dest = "D:\\a\\x\\z"
    os.rename(src,dest)

master = Tk()

def callback():
    global master
    master.after(1, callback)
    copydir()
    print "click!"

b = Button(master, text="OK", command=copydir)
b.pack()

master.after(100, callback)

mainloop()

要重现该问题,请在ms 命令提示符"中打开将重命名的文件夹,以便重命名它会从 Tkinter 代码中抛出异常.

To reproduce the problem, open the folder which it will rename in "ms command prompt" such that renaming it will throw exception from Tkinter code.

我的原始代码使用线程并执行其他任务,因此我尝试使此测试脚本中的操作尽可能相似.

My original code is using threading and is performing other tasks as well, so I have tried to make the operations in this test script as similar as possible.

现在,如果我通过双击运行此代码,则程序将直接关闭而不会引发任何错误.但是如果我一直从控制台运行这个脚本,那么异常消息就会被转储到控制台上,至少我知道,出了点问题.

Now, if I run this code by double clicking it, then program simply closes without throwing any error. But If I had been running this script from console, then exception messages are dumped on the console and atleast I got to know , something is wrong.

我可以通过在尝试重命名的代码中使用 try/catch 来修复此代码,但我也想通知用户此失败.所以我只想知道在编写 Tkinter 应用程序时应该遵循哪些编码方法,我想知道:-

I can fix this code by using try/catch in the code where it tried to rename but I want to inform user about this failure as well. So I just want to know what coding approaches should be followed while writing Tkinter App's and I want to know:-

1) 每当用户通过双击运行它时,我可以让我的脚本在文件中转储一些堆栈跟踪吗?至少,我会知道出了什么问题并修复它.

1) Can I make my script dump some stack trace in a file whenever user ran this by double clicking on it. By this atleast, I would know something is wrong and fix it.

2) 我能否阻止 tkinter 应用程序在出现此类错误时退出并在某些 TK 对话框中抛出任何异常.

2) Can I prevent the tkinter app to exit on such error and throw any exception in some TK dialog.

感谢您的帮助!!

推荐答案

您可以覆盖 Tkinter 的 CallWrapper.为此,必须使用 Tkinter 的命名导入而不是通配符导入:

You can override Tkinter's CallWrapper. It is necessary to use a named import of Tkinter instead of a wildcard import in order to do so:

import Tkinter as tk
import traceback

class Catcher: 
    def __init__(self, func, subst, widget):
        self.func = func 
        self.subst = subst
        self.widget = widget
    def __call__(self, *args):
        try:
            if self.subst:
                args = apply(self.subst, args)
            return apply(self.func, args)
        except SystemExit, msg:
            raise SystemExit, msg
        except:
            traceback.print_exc(file=open('test.log', 'a'))

# ...
tk.CallWrapper = Catcher
b = tk.Button(master, text="OK", command=copydir)
b.pack()
master.mainloop()

这篇关于在 python tkinter 中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆