Python Tkinter Animation

后端 未结 3 937
猫巷女王i
猫巷女王i 2021-02-04 21:04

Why is the animation not working? The shape doesn\'t move when I run the program.

from Tkinter import *
import time



class alien(object):
     def __init__(sel         


        
3条回答
  •  离开以前
    2021-02-04 21:48

    Your animation method has a while True loop in it which never breaks. This is a no-no in a GUI program, because by never returning, it prevents the GUI's event-loop from processing events. So, for example, if you had a Menu, then the user would not be able to select any menu item. The GUI would appear frozen, except for whatever actions you implement in the animation method.

    Here is a slight modification of @Tim's code which fixes this problem by removing the while loop and simply moving the aliens one step before returning. self.master.after is called at the end of the animation method to have the event loop call animation again after a short pause.


    import tkinter as tk
    import time
    
    class Alien(object):
        def __init__(self, canvas, *args, **kwargs):
            self.canvas = canvas
            self.id = canvas.create_oval(*args, **kwargs)
            self.vx = 5
            self.vy = 0
    
        def move(self):
            x1, y1, x2, y2 = self.canvas.bbox(self.id)
            if x2 > 400:
                self.vx = -5
            if x1 < 0:
                self.vx = 5
            self.canvas.move(self.id, self.vx, self.vy)
    
    class App(object):
        def __init__(self, master, **kwargs):
            self.master = master
            self.canvas = tk.Canvas(self.master, width=400, height=400)
            self.canvas.pack()
            self.aliens = [
                Alien(self.canvas, 20, 260, 120, 360,
                      outline='white', fill='blue'),
                Alien(self.canvas, 2, 2, 40, 40, outline='white', fill='red'),
            ]
            self.canvas.pack()
            self.master.after(0, self.animation)
    
        def animation(self):
            for alien in self.aliens:
                alien.move()
            self.master.after(12, self.animation)
    
    root = tk.Tk()
    app = App(root)
    root.mainloop()
    

提交回复
热议问题