Daijoubu
Daijoubu

Reputation: 63

How to add text to a canvas from a list

So essentially I have this line:

StoreItems = random.sample(set(['sword','pickaxe','toothpick','hammer','torch','saw']), 5)

Which randomly chooses 5 strings from the list. I want to put those 5 randomly chosen onto my Tkinter canvas as seperate text's with canvas.create_text.

Upvotes: 0

Views: 1056

Answers (1)

falsetru
falsetru

Reputation: 369274

Iterate over the store_items:

import random
from tkinter import *


store_items = random.sample(['sword','pickaxe','toothpick','hammer','torch','saw'], 5)


root = Tk()
canvas = Canvas(root)
canvas.pack()
XBASE, YBASE, DISTANCE = 10, 20, 20
for i, word in enumerate(store_items):  # <-- iterate words using `for` loop.
    canvas.create_text(
        (XBASE, YBASE + i * DISTANCE),
        text=word, anchor=W, fill='blue')
root.mainloop()

Demo screenshot

UPDATE To make clicking on the word trigger some action, you need to bind a event (<1> or <Button-1>) to an event handler.

import random
from tkinter import *


store_items = random.sample(['sword','pickaxe','toothpick','hammer','torch','saw'], 5)


root = Tk()
canvas = Canvas(root)
canvas.pack()
XBASE, YBASE, DISTANCE = 10, 20, 20
for i, word in enumerate(store_items):  # <-- iterate words using `for` loop.
    canvas.create_text(
        (XBASE, YBASE + i * DISTANCE),
        text=word, anchor=W)

def onclick(e):
    found = canvas.find_closest(e.x, e.y)
    if found:
        canvas.itemconfig(found[0], fill='blue')
canvas.bind('<1>', onclick)

root.mainloop()

Upvotes: 2

Related Questions