Python/Tkinter事件参数Issu

2024-09-24 22:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

< >我的代码似乎运行良好,棕色方块出现在空白窗口中,直到我尝试按下一个键,当我这样做时,除了出现错误消息之外什么也没有发生。有什么想法吗?在

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)

按右箭头键时的错误消息:

^{pr2}$

Tags: selfevent消息moveondef错误tk
1条回答
网友
1楼 · 发布于 2024-09-24 22:21:10

在对象内部调用函数时,self(对象的实例)作为第一个参数发送。您可以使用一些方法来撤消它,staticmethod是最常见的方法,但在这种情况下,这不是您要寻找的。在

您得到的错误表明解释器发送了这个self参数和常规的event参数,但是您的方法只得到一个参数,并且无法处理它们。在

确保除了其他参数之外,所有函数都将self(或您选择的任何名称,如inst)作为第一个参数:

def on_keyrelease(self, event):

moveon_keypress也是如此。在

相关问题 更多 >