python - 在 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
这可能是愚蠢的,但我对此还是很陌生。谢谢。
解决方案
谢谢。问题是我的create_lines
函数没有返回任何东西。我也没有在.bind
.
推荐阅读
- c# - C# 表单类扩展问题
- ocaml - LSP 服务器示例
- ios - 即使启用了设备“请勿打扰”,如何显示 VoIP 推送呼叫的传入 CallKit 窗口?
- onnx - caffe2 推断 onnx 模型,发生 IndexError: Input 475 is undefined
- java - 在Java中减少扩展数量以尽可能减少类的最佳方法是什么?
- c++ - QtQuick - QQuickItem mouseMoveEvent 不工作
- powershell - 加入域后设置自动登录到本地用户
- java - 具有唯一元素的 Java 线程安全并发队列
- android - React-native:允许在 Android 中使用音频的权限
- c++ - 在 connect() 调用中看不到我的服务器名称的 arduino 变量