键绑定不工作tkinter

时间:2018-05-20 00:46:20

标签: python tkinter

当您按下向左箭头时,此代码应该使坦克向左移动,但它似乎不起作用:

from tkinter import *
from tkinter.constants import LEFT
root = Tk()
c = Canvas(root, width=400, height=400)
tank = c.create_rectangle(200,200,250, 250, outline = 'dark green', 
fill='dark green')
c.pack()

class tank:
    def move_left(self):
        c.move(tank, -200, 0)
c.bind('<Left>', tank.move_left(tank))
c.focus_set()            
root.mainloop()            

2 个答案:

答案 0 :(得分:1)

这里有两个问题:

  • c.bind('<Left>', tank.move_left(tank))中,您实际上将tank.move_left的返回值传递给c.bind第二个参数;并且返回值为None

  • 您定义了一个名为tank的变量,然后使用名为tank的类覆盖该变量。

解决这两个问题:

from tkinter import *
from tkinter.constants import LEFT
root = Tk()
c = Canvas(root, width=400, height=400)
tank = c.create_rectangle(200,200,250, 250, outline = 'dark green', fill='dark green')
c.pack()

class Tank: # Pascal case is the recommended naming convention for classes
    def move_left(self):
        c.move(tank, -200, 0)

c.bind('<Left>', Tank.move_left) # Passing the function and not its return value as 2nd argument
c.focus_set()            
root.mainloop()     

答案 1 :(得分:0)

这是基于Reblochon Masque现已删除的答案的版本。如果他发布自己的修复版本,我将删除这个。

webview

当然,你真的不需要这么简单的课程。

import tkinter as tk

class Battlefield(tk.Canvas):
    def __init__(self, master):
        self.master = master
        super().__init__(root, width=400, height=400)
        self.pack()

        tank = Tank(self)

        self.bind('<Left>', tank.move)
        self.bind('<Right>', tank.move)
        self.bind('<Up>', tank.move)
        self.bind('<Down>', tank.move)

class Tank:
    OFFSETS = {'Left': (-1, 0), 'Right': (1, 0), 'Up': (0, -1), 'Down': (0, 1)}

    def __init__(self, canvas):
        self.canvas = canvas
        self.id = self.canvas.create_rectangle(200, 200, 250, 250, outline='dark green', fill='dark green')

    def move(self, event):
        self.canvas.move(self.id, *Tank.OFFSETS[event.keysym])

if __name__ == '__main__':
    root = tk.Tk()
    battlefield = Battlefield(root)
    battlefield.focus_set()
    root.mainloop()