python - 如何使用 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 时,它们都会被删除而不是最后一个一。
这对我的项目的推进没有太大帮助,但我希望能够了解这里发生的事情。
解决方案
有不同的场景可以做你正在寻找的事情。
这是一个想法,您可以根据您的确切需求对其进行调整:
在您的位置,我将依靠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()
推荐阅读
- node.js - Apollo 客户端:未定义变量。收到状态码 400
- java - 如何在返回整个(修改后的)字符串的同时用 replaceAll() 替换捕获组?
- eclipse - STS-添加服务器-当我尝试添加 oracle weblogic 服务器时,下一步按钮被禁用
- c - 在 C 中通过 UDP 在结构中发送动态数组
- outlook - 以编程方式读取自定义 Outlook 表单字段
- woocommerce - 如果用户未登录,Woocommerce 不显示 COD 付款选项
- react-native - 如何将图像 url 作为道具传递给另一个组件?
- python - cx_Freeze Exe 应用程序一打开就关闭,没有任何错误
- javascript - Sumoselect 中的选项可以添加图标/图像吗?
- java - 在 reducer 中重复数据删除工作不如预期