如何使类中的对象在画布上移动?下面是一些代码,它只对形状有效,但对对象无效。我不擅长类和对象。如果你能帮助我,我将不胜感激
from tkinter import *
root = Tk()
sirka = root.winfo_screenwidth()
vyska = root.winfo_screenheight()
canvas = Canvas(root , height = vyska,width = sirka,bg= "gray")
canvas.place(x = -2,y = -2)
root.attributes("-fullscreen",True)
ex = Button(root,text = 'exit',command =root.destroy)
ex.place(x =sirka - 27,y =0)
x1 = 400
y1 = 200
class stickman(object):
def __init__(self,head,body):
self.head = head
self.body = body
man = stickman(canvas.create_oval(x1,y1,x1+20,y1+20,fill = 'black'), canvas.create_rectangle(x1-10,y1+20,x1+30,y1+60,fill ='red' ))
def move(event):
global x1, y1
if event.char == "a":
canvas.move(man, -10, 0)
elif event.char == "d":
canvas.move(man, 10, 0)
elif event.char == "w":
canvas.move(man, 0, -10)
elif event.char == "s":
canvas.move(man, 0, 10)
root.bind("<Key>", move)
mainloop()
你必须分开移动每个元素
或在类中创建方法
然后你可以使用
编辑:移动更平滑的
<KeyPress>
和<KeyRelease>
更改man.speed_x
、man.spee_y
和root.after()
每100ms
运行一次update_game
编辑:正如Bryan Oakley在评论中提到的-您还可以将同一标记指定给许多对象,并使用此标记移动所有对象
相关问题 更多 >
编程相关推荐