首页 > 解决方案 > 如何使用 Canvas.create_image

问题描述

我目前正在做一个项目,我有一个坏主意,直到现在才测试我的代码。

我已经获得了几个错误,但我在这里只公开其中一个,我试图将其减少到最低限度。

这是我的代码:

from tkinter import *

root = Tk()
can = Canvas(root, height = 200, width = 300, bg = "white")
can.tab = [{} for k in range(5)]
nb = 0

def del(event):
    global can, nb
    can.tab[nb-1] = {}
    nb -= 1

def click(event):
    global can, nb
    x,y = (event.x)//50 * 50, (event.y)//50 * 50
    can.tab[nb]['image'] = PhotoImage(master = can, file = "mouse_pointer.png", name = "mouse_pointer") #Removing the name definition makes it work
    can.create_image(x, y, anchor = NW, image = can.tab[nb]['image'])
    nb += 1

can.focus_set()
can.bind("<Button-1>", click)
can.bind("<Delete>", del)

can.pack()
root.mainloop()

这段代码的目的是创建一个画布,当你点击它时,它会在你点击的地方创建一个图像,当你按下 del 时,它会使最后创建的图像消失。

问题如下 如果我不给我的图像命名,它可以正常工作,但是当我给它们一个名字时(它们都有相同的!),当我按下 del 时,它们都会被删除而不是最后一个一。

这对我的项目的推进没有太大帮助,但我希望能够了解这里发生的事情。

标签: pythoncanvastkinter

解决方案


有不同的场景可以做你正在寻找的事情。

这是一个想法,您可以根据您的确切需求对其进行调整:

在您的位置,我将依靠delete()将创建的图像的 id 删除的函数。all它也可以通过传递' '参数来删除画布上所有现有的图像。

为了解决您的问题,您可以例如将您创建的图像的 ID(我猜是其中的五个)存储到堆栈(列表或其他任何内容,正如我所说的,取决于您的具体情况,因为您的示例非常对我来说模糊),然后按照 LIFO 删除它们:

from tkinter import *

root = Tk()
can = Canvas(root, height = 200, width = 300, bg = "white")
can.tab = [{} for k in range(5)]
nb = 0

stack_ids = [] # added this
def bell(event):
    can.delete(stack_ids.pop()) #modified your function here

def click(event):
    global can, nb
    x,y = (event.x)//50 * 50, (event.y)//50 * 50
    can.tab[nb]['image'] = PhotoImage(master = can, file = "mouse_pointer.png", name = "mouse_pointer") 
    id = can.create_image(x, y, anchor = NW, image = can.tab[nb]['image'])
    stack_ids.append(id) # save the ids somewhere


can.focus_set()
can.bind("<Button-1>", click)
can.bind("<Delete>", bell)

can.pack()
root.mainloop()

推荐阅读