我想让sprite在画布上四处移动,并尝试使用键绑定作为控件。当我运行该程序时,它不会移动,直到我尝试正确的密钥。我用鼠标按钮进行测试,它工作正常。如何修复tkinter中的键绑定
添加代码:
from tkinter import *
class MainGame:
def __init__(self):
self.grid = [[""]*15 for n in range(15)]
self.grid[14][3] = 1
print(self.grid)
self.canvas = Canvas(root, width = 900, height = 900)
self.canvas.pack()
self.a, self.b = 45, 175
def noreaction(self, event):
print("It clicked")
print(self.a)
self.a += 50
self.b += 50
self.canvas.create_image(self.a, self.b, image = self.pl, tags = "p2Tag")
self.canvas.delete("p1Tag")
self.canvas.tag_bind("p2Tag", "<Key-q>", self.noreaction)
def run(self):
self.pl = PhotoImage(file = "player.png")
self.canvas.create_image(self.a, self.b, image = self.pl, tags = "p1Tag")
self.canvas.tag_bind("p1Tag", "<Key>", self.noreaction)
self.x0, self.y0, self.x1, self.y1 = -30, 150, 20, 200
for self.row in self.grid:
for self.column in self.row:
self.x0 += 50
self.x1 += 50
self.cell = self.canvas.create_rectangle(self.x0, self.y0, self.x1, self.y1)
self.y0 += 50
self.y1 += 50
self.x0 = -30
self.x1 = 20
root = Tk()
root.focus_set()
obj = MainGame()
obj.run()
root.mainloop()
请将您的代码发布为文本而不是图片。不想重新输入所有的代码。 –
您添加绑定的组件可能没有焦点。尝试在根级别使用'bind_all'。 –
请不要发布一个链接到另一个网站上的代码。花时间在问题本身发布[mcve]。如果你不愿花时间写出一个好问题,大多数人都不愿花时间写出一个好答案。 –