我花了很多时间在我对another question的回答中调试和修改errorwindow.py模块,因此它可以在Python 2和3中工作 – 链接答案中的代码是为Python 2.x编写的.注意我只做了使它在两个版本下运行所需的最低要求.该脚本的修改版本已命名为errorwindow3k.py(尽管它也适用于Python 2).
大多数问题仅仅是由于模块重命名,但是有一个更难以理解,结果是由于切换到Unicode字符串是版本3中的默认字符串类型 – 显然(在Windows上无论如何) ,进程之间的管道是字节流,而不是Unicode字符.幸运的是,解码然后在另一端编码数据的“修复”在Python 2中也没有受到影响,这使得纠正问题变得相当容易.
这个好处是使用它非常容易.只需导入它,并从发送到sys.stderr或sys.stdout的任何输出上的那一点将导致基于tkinter的输出窗口显示为显示信息所需.在您的示例代码中,只需在print之前的某处插入importwindwindow3k(“Hello world”).
文件errorwindow3k.py:
# Code derived from Bryan Olson's source posted in this related Usenet discussion:
# https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/TpFeWxEE9nsJ
# https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/eEHYAl4dH9YJ
#
# See the comments and doc string below.
#
# Here's a module to show stderr output from console-less Python
# apps, and stay out of the way otherwise. I plan to make a ASPN
# recipe of it, but I thought I'd run it by this group first.
#
# To use it, import the module. That's it. Upon import it will
# assign sys.stderr.
#
# In the normal case, your code is perfect so nothing ever gets
# written to stderr, and the module won't do much of anything.
# Upon the first write to stderr, if any, the module will launch a
# new process, and that process will show the stderr output in a
# window. The window will live until dismissed; I hate, hate, hate
# those vanishing-consoles-with-critical-information.
#
# The code shows some arguably-cool tricks. To fit everthing in
# one file, the module runs the Python interpreter on itself; it
# uses the "if __name__ == '__main__'" idiom to behave radically
# differently upon import versus direct execution. It uses TkInter
# for the window, but that's in a