Skip to main content
 首页 » 编程设计

python之tkinter( python ): assign class method to a key

2025年02月15日10artech

在我的简单代码中,一个红球沿直线下落(有效)。当我按下右箭头键时,我希望球也向右 move 。但是,这不起作用。我做错了什么?

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') 
 
    def gravity(self): 
        self.canvas.move(self.bird, 0, 10) 
        self.canvas.after(200, self.gravity) 
 
    def moveRight(self, event): 
        self.canvas.move(self.bird, 10, 0) 
        self.canvas.after(200, self.moveRight) 
 
bird = Bird(canvas, (100, 100, 110, 110)) 
 
bird.gravity() 
 
canvas.bind('<Right>', bird.moveRight) 
 
root.mainloop() 

我还有一个问题:

是否可以为整个 Canvas 调用此“after”函数或类似函数,而不是分别调用这两种方法?

如果您发现我的代码有任何其他缺陷,请告诉我!

谢谢!

请您参考如下方法:

必须在类内部将右键绑定(bind)到 Canvas 上,并将焦点设置在 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('<Right>', 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()