我正在关注一个 youtube 教程: https://www.youtube.com/watch?v=Zf-b2JVZs7g
当我们到达 sys.exit(0)
Python shell 似乎正在响应,但我创建的窗口锁定而不是关闭。另一件奇怪的事情是,当我运行调试器时,程序按预期运行。
#Python 2.7.8
#Idle 2.7.8
#Tkinter 8.5.15
import sys
import Tkinter
import turtle
from Tkinter import *
def main():
root = Tk()
root.title("Draw!")
root.geometry("800x800")
cv = Canvas(root, width=600, height=600)
cv.pack(side=LEFT)
t = turtle.RawTurtle(cv)
screen = t.getscreen()
screen.setworldcoordinates(0,0,600,600)
frame = Frame(root)
frame.pack(side = RIGHT, fill = BOTH)
screen.tracer(0)
def quitHandler():
print ("Goodbye")
sys.exit(0)
##raise SystemExit
##exit()
quitButton = Button(frame, text="Quit", command = quitHandler)
quitButton.pack(side=BOTTOM)
def clickHandler(x,y):
t.goto(x,y)
screen.update()
screen.onclick(clickHandler)
def dragHandler(x,y):
t.goto(x,y)
screen.update()
t.ondrag(dragHandler)
root.mainloop()
if __name__ == "__main__":
main()
在视频的评论中,有两件事让我印象深刻,但我不明白为什么 sys.exit(0) 对我不起作用,就像对他一样:
- 他正在使用 Python 3
- 其他人也有同样的问题,但我看不到任何答案。
我的猜测是版本问题,但(作为 n00b)我不知道问题出在哪里。
请您参考如下方法:
将 root.destroy() 行添加到您的 quitHandler 函数中。它将清理以其他方式留下的 Tkinter 进程。我对其进行了测试,它解决了我的问题。
(代码已删除)
更新
来自 Terry Jan Reedy 的评论:
The details of Python shutdown have changed from version to version, even within 3.x. I personally would put root.destroy() but not sys.exit() in a quit handler, and would let Python exit normally after mainloop() and main() call return. Since printing 'goodbye' does not print to the gui, and could fail (if you run the app with pythonw on windows), I would put the print after the main() call.
原来如此
def quitHandler():
root.destroy()
和 print 在代码的最后。
