user3836103
user3836103

Reputation: 135

How to move a rectangle to the position of another rectangle, of different size, with tkinter

I'm quite new to Python, and coding in general, and recently I started a simple (or not-so-simple) project of making a revamped version of the classic Space Invaders using tk in the form of tkinter. I came upon a problem, though, which I had no idea how to fix: how to move a rectangle(the bullet) to another rectangle(the spaceship). I created the bullet by creating them at 0, 0 , but then I don't know how to move them exactly to the spaceship. Thanks!

There's probably an easy solution that I haven't stumbled upon.

Upvotes: 0

Views: 8198

Answers (2)

Jeremy Kerr
Jeremy Kerr

Reputation: 47

When you create something on the canvas initially (such as the rectangle), you can store the item id by saving the result to a variable, like

square = canv.create_rectangle(bbox, **options)

Later, you can use move, itemconfig, or itemconfigure to move the object someplace else, like

canv.move(square, dx, dy)

where dx and dy are the offsets from current position.

Alternatively, if you want to make an object out of multiple shapes, you can assign tags to them and manipulate the object all at once by tags, as follows:

canv.create_rectangle(bbox, tags=('square'))
canv.move('square', dx, dy)

Two resources I found very useful were http://www.tkdocs.com/tutorial/canvas.html and http://effbot.org/tkinterbook/canvas.htm

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 385830

Assuming that you're drawing the rectangle on a canvas, you can use the move method of the canvas to move an item from its current position to a new position.

Upvotes: 0

Related Questions