简体   繁体   中英

Python Tkinter window.mainloop()

I have copied the following code to experiment with animations using Tkinter:

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()

This works fine, but what I have noticed is that it seems to work the same with and without the line window.mainloop() . Furthermore, this line seemingly would never be called, because the prevailing while loop never breaks. However, I have seen this example code many times, so it seems that window.mainloop() does perform something important. What is that thing??

window.mainloop() does not allow python interpreter to execute codes after that line until the the application is closed. For example you can add some print statements after the window.mainloop() you will find that python prints them after you close you app.

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

In this way the program loops within the mainloop allowing buttons and other widgets to perform multiple times, else program would not execute after first execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM