gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:20 29 4
gpt4 key购买 nike

在我的简单代码中,一个红球沿直线下落(有效)。当我按下右箭头键时,我希望球也向右 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()

关于python - tkinter( python ): assign class method to a key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46461706/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com