以下是代码:
from tkinter import *
class Main:
def __init__(self):
self.root = Tk()
self.canvas = Canvas(self.root, width="600", height="400")
self.canvas.pack()
self.r1 = self.canvas.create_polygon(20, 0, 20, 20, 40, 10, fill='red')
self.loop()
def keypress(self, event):
x, y = 0, 0
if self.event.char == "a":
x = -4
if self.event.char == "d":
x = 4
if self.event.char == "w":
y = -4
if self.event.char == "s":
y = 4
self.canvas.move(self.r1, x, y)
def loop(self):
self.root.bind_all("<Key>", self.keypress)
self.root.mainloop()
main = Main()
该代码输出AttributeError: 'Main' object has no attribute 'event'
我已经尝试添加self.event = Event
,但它将显示错误AttributeError: type object 'Event' has no attribute 'char'
如果需要,请询问更多信息。
Ps。对不起,我的英语不好,我是初学者,所以请不要评判。
更改您的方法:
def keypress(self, event):
x, y = 0, 0
if event.char == "a":
x = -4
if event.char == "d":
x = 4
if event.char == "w":
y = -4
if event.char == "s":
y = 4
self.canvas.move(self.r1, x, y)
您尝试了self.event
。你只需要event