Daijoubu
Daijoubu

Reputation: 63

How do I match text location to randomly placed text on my Canvas?

I have the function:

StoreItems = random.sample(set(['sword','pickaxe','toothpick','hammer','torch','saw']), 5)
#Selects 5 Random strings from the list. ^

XBASE, YBASE, DISTANCE = 300, 320, 50
for i, word in enumerate(StoreItems):  
    canvas.create_text(
        (XBASE, YBASE + i * DISTANCE),
        text=word, activefill="Medium Turquoise", anchor=W, fill="White", font=('Anarchistic',40), tags=word)

canvas.tag_bind('sword', '<ButtonPress-1>', BuySword)
canvas.tag_bind('pickaxe', '<ButtonPress-1>', BuyPick)
canvas.tag_bind('toothpick', '<ButtonPress-1>', BuyTooth)
canvas.tag_bind('hammer', '<ButtonPress-1>', BuyHammer)
canvas.tag_bind('torch', '<ButtonPress-1>', BuyTorch)
canvas.tag_bind('saw', '<ButtonPress-1>', BuySaw)

Which randomly selects from the list: StoreItems[] and puts 5 of them on my canvas in a random order. If I wanted my tag binds to create text next to them how would I do that?

I have the event functions:

def BuySword(event):
if 'sword' in StoreItems:
    sword = canvas.create_text((420,350), text="test", fill="White", font=('Anarchistic',40))

But I want the location of this created text to follow the random placement of the corresponding word from my list.

Upvotes: 0

Views: 78

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

you can use the bbox method to get the position of a tagOrId:

Returns a tuple (x1, y1, x2, y2) describing a rectangle that encloses all the objects specified by tagOrId. If the argument is omitted, returns a rectangle enclosing all objects on the canvas. The top left corner of the rectangle is (x1, y1) and the bottom right corner is (x2, y2).

although since you are doing relative position all you need is the first two:

def BuySword(event):
    if 'sword' in StoreItems:
        x,y,_,_ = canvas.bbox("sword")
        relative_position = (x+420,y)
        sword = canvas.create_text(relative_position, text="test", fill="White", font=('Anarchistic',40),
                                   anchor=N+W) #the anchor is needed to line up with the north west corner of the original text

Upvotes: 1

Related Questions