tkinter (python): assign class method to a key

后端 未结 2 1290
有刺的猬
有刺的猬 2021-01-22 17:13

In my simple code, a red ball is falling down in a straight line (that\'s working). When I push the right arrow key, I want the ball to also move in right direction. This is no

2条回答
  •  无人及你
    2021-01-22 17:42

    You must bind the right key to the canvas inside the class, and set the focus on the canvas:

    from tkinter import *
    
    root = Tk()
    
    canvas = Canvas(root, height=400, width=500, background='black')
    canvas.pack()
    
    
    class Bird:
        def __init__(self, canvas, coords):
            self.canvas = canvas
            self.coords = coords
            self.bird = canvas.create_rectangle(coords, fill='red')
            self.canvas.bind('', self.moveRight)
            self.canvas.focus_set()
    
        def gravity(self):
            self.canvas.move(self.bird, 0, 10)
            self.canvas.after(200, self.gravity)
    
        def moveRight(self, event=None):
            self.canvas.move(self.bird, 10, 0)
            self.canvas.after(200, self.moveRight)
    
    
    bird = Bird(canvas, (100, 100, 110, 110))
    
    bird.gravity()
    
    root.mainloop()
    

提交回复
热议问题