Skip to content Skip to sidebar Skip to footer

How To Add Text To Canvas From A List As Separate Canvas.create_text

I have a list: StoreItems = random.sample(set(['sword','pickaxe','toothpick','hammer','torch','saw']), 5) and additional lines which add those 5 strings chosen onto my canvas, and

Solution 1:

Here's what my solution was:

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

XBASE, YBASE, DISTANCE = 300, 340, 50for i, word inenumerate(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)

by setting the (tags=word) and making the tag.bind the same as the corresponding words it would assign that tag to only that word.

Solution 2:

lets say your callback had an item argument as well as the event

def Buy(event,item):
    canvas.itemconfigure(item,fill="red")

then you can loop over the items in your store creating a unique callback wrapper for each like this:

for item in StoreItems:
    def Buy_Wrapper(event, item = item):
        Buy(event, item)
    canvas.tag_bind(item,"<Button-1>",Buy_Wrapper)

or the same thing inline with lambda expressions but I personally find them hard to read

for item in StoreItems:
    canvas.tag_bind(item,"<Button-1>",lambda event,item=item:Buy(event,item))

or with functools.partial specifying the keyword argument:

from functools import partialfor item in StoreItems:
    canvas.tag_bind(item,"<Button-1>",partial(Buy,item=item))

Post a Comment for "How To Add Text To Canvas From A List As Separate Canvas.create_text"