自动移动对象

时间:2018-01-27 04:47:54

标签: python tkinter tkinter-canvas

我练习的目的是制作一个游戏,其中一个落球需要被屏幕底部的一个栏杆抓住。下面的代码不会使球自动下降。我在下面的帖子中提到过,但找不到解决方案: Tkinter bind to arcAutomatically Moving Shape? Python 3.5 Tkinter

import tkinter as tk


class Game(tk.Tk):
     def __init__(self):
         tk.Tk.__init__(self)
         self.can = tk.Canvas(self, width=400, height=400)
         self.can.pack(fill="both", expand=True)
         self.ball = self.can.create_oval(40, 40, 60, 60, fill="red", tag="ball")
         self.player = self.can.create_rectangle(300,345,350,360, fill="red")
         self.bind("<Key>", self.move_player)
         self.can.tag_bind("ball",self.move_b)
         self.mainloop()

    def move_b(self,event=None):
         self.can.move(self.ball, 1, 0)
         print(self.ball)
         # move again after 25ms (0.025s)
         self.can.after(25, self.move_b)

    def move_player(self, event):
        key = event.keysym
        if key == "Left":
           self.can.move(self.player, -20, 0)
        elif key == "Right":
            self.can.move(self.player, 20, 0)

if __name__ == '__main__':
Game()

1 个答案:

答案 0 :(得分:0)

tag_bind的第二个位置参数是一个事件,而在您的代码中,它作为实际回调传递,self.move_b。首先,添加一个事件:

self.can.tag_bind("ball", "<ButtonRelease-1>", self.move_b)

如果您不希望它有活动,只需传递None

self.can.tag_bind("ball", None, self.move_b)

或根本不使用tag_bind,只需致电:

self.move_b()

每当你想要动画开始时。