【问题标题】:How to add text to canvas from a list as separate canvas.create_text如何将列表中的文本作为单独的 canvas.create_text 添加到画布
【发布时间】:2016-03-25 19:37:25
【问题描述】:

我有一个清单:

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

以及将选择的这 5 个字符串添加到我的画布上并给它们绑定的附加行。

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))

found = canvas.find_closest(XBASE, YBASE)
if found:
    canvas.itemconfig(found[0])
    canvas.bind('<1>', Buy)

问题是我需要为每个单词分配一个不同的标签绑定,目前它为所有单词提供相同的绑定。所以我不能让点击saw 得到不同的结果,而不是点击toothpick

【问题讨论】:

  • 我了解 tag.binds 的使用,如上面的链接所示。问题出在我列出的示例中,它将列表中的所有项目显示为一个对象。我需要给列表中的每个项目一个单独的标签。当他们在一起时,我不能这样做。
  • ...canvas.tag_bind("sword","&lt;1&gt;",Buy_Sword) 大概?如果您需要将参数传递给Buy,那么您可以使用functools.partial from functools import partial ; ... canvas.tag_bind(word,"&lt;1&gt;",partial(Buy,word))
  • 我从未使用过 functools.partial。你能告诉我这将如何与我上面的内容一起工作吗?在更大的意义上。我的意思是。我有一个 def buy(event) 但我不知道如何让它从一个词中触发。对不起,我有点新手。
  • 没关系,每个人都开始一个新手,你有text=word,你可以在它之后添加tags=word,这样任何带有标签或id的method on the Canvas Widget都可以被赋予它关联的词到。然后查看any of the answers here 以获取额外的参数。我真的不想发布答案,因为这是重复的。祝你好运!

标签: python python-3.x tkinter tk


【解决方案1】:

这是我的解决方案:

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

XBASE, YBASE, DISTANCE = 300, 340, 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)

通过设置 (tags=word) 并使 tag.bind 与相应的单词相同,它将将该标签分配给仅该单词。

【讨论】:

  • 您忘记显示BuySword 和其他人的定义,但我很高兴您能够弄清楚! :D
【解决方案2】:

假设您的回调有一个 item 参数以及事件

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

然后您可以循环访问商店中的项目,为每个项目创建一个独特的回调包装器,如下所示:

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

或与lambda 表达式内联的相同内容,但我个人觉得它们很难阅读

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

或使用functools.partial 指定关键字参数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多