tkinter(python):将类方法分配给键 [英] tkinter (python): assign class method to a key

查看:97
本文介绍了tkinter(python):将类方法分配给键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 not working, however. What am I doing wrong?

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()

我还有另一个问题:

是否可以为整个画布调用此之后"功能或类似功能,而不是分别调用这两种方法?

Is it possible to call this "after"-function or a similar function for the whole canvas instead of the two methods separately?

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

If you see any other flaws with my code plz let me know!

谢谢!

推荐答案

您必须将右键绑定到类内部的画布上,并将焦点设置在画布上:

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('<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()

这篇关于tkinter(python):将类方法分配给键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆