2016-03-08 1253 views
1

我已经复制下面的代码使用的Tkinter与动画实验:Python的Tkinter的window.mainloop()

from Tkinter import * 
window = Tk() 
canvas = Canvas(window, width = 400, height = 300) 
canvas.pack() 
x0 = 10 
y0 = 50 
x1 = 60 
y1 = 100 
i = 0 
deltax = 2 
deltay = 3 
which = canvas.create_oval(x0,y0,x1,y1,fill="red", tag='redBall') 
while True: 
    canvas.move('redBall', deltax, deltay) 
    canvas.after(20) 
    canvas.update() 
    if x1 >= 400: 
     deltax = -2 
    if x0 < 0: 
     deltax = 2 
    if y1 > 300: 
     deltay = -3 
    if y0 < 0: 
     deltay = 3 
    x0 += deltax 
    x1 += deltax 
    y0 += deltay 
    y1 += deltay 
window.mainloop() 

这工作得很好,但我已经注意到的是,它似乎工作同样有和无该行window.mainloop()。此外,这条线似乎永远不会被调用,因为普遍的while循环从不中断。不过,我已经多次看过这个示例代码,所以看起来window.mainloop()确实执行了一些重要的事情。那个东西是什么??

+1

因为在它上面有一个无限的'while True:'循环,代码永远不会到'window.mainloop()'。通常你会使用'mainloop()'来启动Tkinter事件处理程序,但是在这个'canvas.update()'中导致窗口在整个循环中被显示和更新。 – Jkdc

回答

0

window.mainloop()不允许Python解释器在该行之后执行代码,直到应用程序关闭。例如,你可以在window.mainloop()之后添加一些打印语句,你会发现python在关闭你的应用程序后打印它们。

from Tkinter import * 
root=Tk() 
#your code here 
root.mainloop() 
#now print 
print 'Mainloop over' 

这样的程序循环主循环使按钮和其他部件进行多次内,否则程序将不会第一次执行后执行。