基本上我有这条线:
StoreItems = random.sample(set(['sword','pickaxe','toothpick','hammer','torch','saw']), 5)
从列表中随机选择5个字符串。我想将随机选择的5个随机选择放在我的Tkinter画布上,作为canvas.create_text的单独文本。
答案 0 :(得分:2)
迭代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()
更新要点击单词触发某些操作,您需要将事件(<1>
或<Button-1>
)绑定到事件处理程序。
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()