【发布时间】:2021-09-22 00:48:51
【问题描述】:
我正在尝试通过我开始的这个新的 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: 错误# args: 应该是“.!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
这可能有些愚蠢,但我对此还是很陌生。谢谢。
【问题讨论】:
-
似乎还有其他问题,例如绑定:
root.bind("<KeyPress-Left>",m.move_left())以这个为例,第一个将立即执行所以你应该使用root.bind("<KeyPress-Left>",m.move_left)但是在这种情况下它仍然会抛出一个错误,因为.bind传递了一个事件参数,因此应该像这样处理:root.bind("<KeyPress-Left>", lambda e: m.move_left())也每个 PEP 8 类名应该是CapitalCase哦,那些你调用的圆和线对象不是对象(技术上它们是但是..) 它们是整数 -
您的
self.lines属性为无,因为create_lines()没有返回任何内容。 -
请尝试edit你的问题包含一个包含minimal reproducible example的代码块。
标签: python oop tkinter tkinter-canvas