在python canvas中移动定义的对象

时间:2018-11-24 23:45:20

标签: python tkinter tkinter-canvas

我想让已定义的对象在画布中移动。我知道有一个命令可以移动对象(.move),但它仅适用于单个项目。那么如何移动由矩形组成的整个定义的对象? 像示例中的那个一样?因为我需要将数百个小物体作为一个物体移动。

x=400
y=400



def player(x,y):
    canvas.create_rectangle(x,y,x+50,y+50,fill='black')
    canvas.create_rectangle(x,y+50,x+150,y+150,fill='red')


def moveright(coordinates2):
    global x
    global y
    x=x+200
    y=y+0
    player(x,y)

def moveleft(coordinates3):
    global x
    global y
    x=x-200
    y=y+0
    player(x,y)

def moveup(coordinates4):
    global x
    global y
    x=x+0
    y=y-150
    player(x,y)

def moveright(coordinates5):
    global x
    global y
    x=x+0
    y=y+150
    player(x,y)



canvas.bind_all('<Right>',moveright)
canvas.bind_all('<Left>',moveleft)
canvas.bind_all('<Up>',moveup)
canvas.bind_all('<Down>',movedown)

1 个答案:

答案 0 :(得分:0)

与您在问题中说的不同,move确实适用于项目组,如果您使用标签:canvas.move(<tag or id>, x, y)

这里是一个例子:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()


def move():
    # move all items with the 'group' tag
    canvas.move('group', 10, 10)


canvas.create_rectangle(10, 10, 30, 30, tags=['group'])
canvas.create_rectangle(20, 40, 50, 70, tags=['group'])
canvas.create_rectangle(60, 50, 80, 60, tags=['group'])

tk.Button(root, text='Move', command=move).pack()
root.mainloop()