Tkinter : Moving more than one object at once
Each time you create a circle/text pair, create a unique tag and associate the tag with both the circle and the text. You can then use this unique tag to move both objects at once.
For example, modify your DragCircle
constructor to look like this:
class DragCircle:
#Constructor
def __init__(self, window, width=100, height=100, colour="red", text = "test"):
self.window = window
tag = "circle-%d" % id(self)
self.circle = self.window._create_circle(width, height, colour, tag)
self.circle_text = self.window._create_text(width, height, text, tag)
Next, modify the _create_circle
and _create_text
functions to accept the tag:
def _create_circle(self, xcoord, ycoord, color, tag):
id_=self.canvas.create_oval(xcoord-25, ycoord-25, xcoord+25, ycoord+25, outline=color, fill=color, tags = ("circledrag", tag))
#This is used to draw text on top of the object on the canvas
def _create_text(self, xcoord, ycoord, text, tag):
self.canvas.create_text(xcoord, ycoord, text = text, tags = ("circledrag", "text", tag))
Finally, modify your OnCircleButtonPress
to get the tag and use it for moving the objects around:
def OnCircleButtonPress(self, event):
...
item = self.canvas.find_closest(event.x, event.y)[0]
tags = self.canvas.gettags(item)
for tag in tags:
if tag.startswith("circle-"):
break
self._drag_data["item"] = tag
...
My proposal which may not be the best
In the constructor you define an association table.
self.assoc = {}
add the method:
def _create_circlewt(self, xcoord, ycoord, color, text):
tc = self.canvas.create_oval(xcoord-25, ycoord-25, xcoord+25, ycoord+25, outline=color, fill=color, tags = "circledrag")
tx = self.canvas.create_text(xcoord, ycoord, text = text)
self.assoc[tc] = tx
in the OnCircleMotion: add the line
self.canvas.move(self.assoc[self._drag_data["item"]], delta_x, delta_y)
just after the other move line
in DragCircle class constructor comment your definition and add the call to _create_circlewt
self.circle_w_text = self.window._create_circlewt(width, height, colour,text)
it works .. I let you enhance the canvas move to enable multiple objects association like
self.assoc[CircleIndex].append(otherobjectIndex)