tkinter (python): assign class method to a key

后端 未结 2 1292
有刺的猬
有刺的猬 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:50

    The problem you are facing is that you are binding keyboard events, but the events can only work if the widget with the bindings has the keyboard focus. You can give the canvas the keyboard focus with focus_set():

    canvas = Canvas(root, height=400, width=500, background='black')
    canvas.focus_set()
    

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

    Yes. Your binding can call any function you want. If you expect to have more than one object and you want them all to move at the same time, you can move them all from a function.

    First, remove the call to after from moveRight. Next, define a global function that calls moveRight for every object. For example:

    def move_them_all():
        bird1.moveRight()
        bird2.moveRight()
        something_else.moveRight()
        self.canvas.after(1000, move_them_all)
    ...
    canvas = Canvas(root, height=400, width=500, background='black')
    ...
    canvas.bind('', move_them_all)
    

提交回复
热议问题