0

I want ot move a defined object in canvas. I know there's a command that moves an object(.move) hovewer it only works on individual items. So how could I move a whole defined object made up of rectangles? Like the one in the example? Because I need to move hundreds of little objects as one.

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
  • Please try to reduce this down to a minimal reproducible example We don't need all the code for all the bindings, just the ones related to moving. We also don't need dozens of canvas items when just one or two will do for the purpose of this question. Commented Nov 26, 2018 at 4:27

1 Answer 1

1

Unlike what you said in the question, move does work for groups of items if you use tags: canvas.move(<tag or id>, x, y).

Here is an example:

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.