我的代码似乎运行正常,棕色方块出现在空白窗口中,直到我尝试按下其中一个键,当我这样做时,除了出现错误信息之外没有任何事情发生。有什么想法吗?
from tkinter import *
x, y, a, b = 50, 50, 100, 100
d = None
vel_dic = {
"Left": ("left", -4, 0),
"Right": ("right", 4, 0),
"Down": ("down", 0, 4),
"Up": ("up", 0, -4)}
class Sprite:
def __init__(self):
self.move
self.x, self.y, self.a, self.b = 50, 50, 100, 100
self.d = 0
self.canvas = Canvas(tk, height = 600, width = 600)
self.canvas.grid(row=0, column=0, sticky = W)
self.coord = [self.x, self.y, self.a, self.b]
self.shape = self.canvas.create_rectangle(*self.coord, outline = "#cc9900", fill = "#cc9900")
def move():
if self.direction != 0:
self.canvas.move(self.rect, self.xv, self.yv)
tk.after(33, move)
def on_keypress(event):
self.direction, self.xv, self.yv = vel_dic[event.keysym]
def on_keyrelease(event):
self.direction = 0
tk = Tk()
tk.geometry("600x600")
sprite1 = Sprite()
tk.bind_all('<KeyPress>', sprite1.on_keypress)
tk.bind_all('<KeyRelease>', sprite1.on_keyrelease)
按右箭头键时出现错误消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keypress() takes 1 positional argument but 2 were given
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keyrelease() takes 1 positional argument but 2 were given
答案 0 :(得分:1)
当调用对象内部的函数时,self
(对象的实例)作为第一个参数发送。您可以使用某些方法撤消该操作,staticmethod
是最常见的方法,但在这种情况下,这不是您要查找的内容。
您收到的错误表明解释器发送了此self
参数和常规event
参数,但您的方法只获取一个参数,并且无法处理它们。
除了其他参数外,请确保所有功能都self
(或您选择的任何名称,如inst
)作为第一个参数:
def on_keyrelease(self, event):
同样适用于move
和on_keypress
。