首页 > 解决方案 > 在 Tkinter 画布中移动对象显示错误 #args 错误

问题描述

我正在尝试通过我开始的这个新的 Tkinter 项目来了解有关 OOP 的更多信息。在这个阶段,我唯一的目标是制作一个由两条线交叉的圆圈,以便通过按键在画布中移动。所以我在这段代码中对线条和圆圈进行了可视化。

def create_circle(circle_pos, r, canvasName, color): #center coordinates, radius
    x = int(circle_pos[0])
    y = int(circle_pos[1])
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1, fill = color)

def create_lines(circle_pos, canvasName, color):
    width = canvasName["width"]
    height = canvasName["height"]
    x = int(circle_pos[0])
    y = int(circle_pos[1])

    x0 = 0
    y0 = y
    x1 = width
    y1 = y

    x2 = x
    y2 = height
    x3 = x
    y3 = 0

    canvasName.create_line(x0, y0, x1, y1, fill = color)
    canvasName.create_line(x2, y2, x3, y3, fill = color)

我将它导入到我的主代码中并且它起作用了。

    from tkinter import *
    import visual
    from movement import movement


    root = Tk()
    root.resizable(width=False, height=False)

    width = 300
    height = 300

    circle_pos = [150, 150]

    canvas = Canvas(root, width = width, height = height)
    canvas.pack()

    lines = visual.create_lines(circle_pos, canvas, "gray30")
    circle = visual.create_circle(circle_pos, 5, canvas, "red2")
    m = movement(canvas, circle, lines)


    root.bind("<KeyPress-Left>",m.move_left())
    root.bind("<KeyPress-Right>",m.move_right())
    root.bind("<KeyPress-Up>",m.move_up())
    root.bind("<KeyPress-Down>",m.move_down())

    mainloop()

然后我创建了用于在画布中移动对象的类,但是当我运行主程序时出现错误:_tkinter.TclError: wrong # args: should be ".!canvas move tagOrId xAmount yAmount"

这是运动代码。

   class movement:
def __init__(self, canvasName, circle_object, lines_object):
    self.x = 0
    self.y = 0
    self.canvasName = canvasName
    self.circle = circle_object
    self.lines = lines_object
    self.motion()       #calling move class to move objects

def motion(self):
    self.canvasName.move(self.circle, self.x, self.y)
    self.canvasName.move(self.lines, self.x, self.y)

    self.canvasName.after(100, self.motion)

def move_up(self):
    self.x = 0
    self.y = -5
def move_down(self):
    self.x = 0
    self.y = 5
def move_left(self):
    self.x = -5
    self.y = 0
def move_right(self):
    self.x = 5
    self.y = 0

这可能是愚蠢的,但我对此还是很陌生。谢谢。

标签: pythonooptkintertkinter-canvas

解决方案


谢谢。问题是我的create_lines函数没有返回任何东西。我也没有在.bind.


推荐阅读