【问题标题】:Python Tkinter remove/delete Image from LabelPython Tkinter 从标签中删除/删除图像
【发布时间】:2016-01-23 00:23:01
【问题描述】:

我有一个带有图像的标签,以及一个应该更新标签/删除标签中图像的按钮,因此我可以通过 label.config 将新图像放入同一标签中。

我尝试使用类似的东西:每当您单击按钮时,它应该使用 label.config(image = None) 删除图像,但它不起作用,如果我将新图像加载到标签中,旧图像仍然存在那里:

    # here is the label initialized 
    global brand_preview
    brand_preview = Label(root, image = None)
    brand_preview.place(x = 10, y = 60)

    # thats the button which have to clear the label image
    self.top_brand = Button(root, text = "clear", bg = "snow3", command=clear_label_image)
    self.top_brand.place(x = 550, y = 60)

    # thats how I load a photoimage into the label
    photoimg_brand = ImageTk.PhotoImage(im_thumb)
    brand_preview.image = photoimg_brand
    brand_preview.config(image = photoimg_brand)

    # Thats how the button works
    def clear_label_image():
        brand_preview.config(image = None)
        brand_preview.image = None

我现在想要的是,如果我们单击按钮,brand_preview 会丢失图像/图像会被删除

编辑: 主要问题已解决,但仅当按钮只需删除图像时才有效。如果我想删除并添加一个新的,它不起作用

def clear_label_image():
    brand_preview.config(image = "")
    photoimg_brand = ImageTk.PhotoImage(im_thumb)
    brand_preview.image = photoimg_brand
    brand_preview.config(image = photoimg_brand)

【问题讨论】:

  • 请发布一个带有可运行代码的最小示例,显示您要修复的行为。
  • 您是否正在保存对新图像的引用?在您的新代码中,photoimg_brand 将被垃圾收集并在 clear_label_image() 完成后立即消失。

标签: python image tkinter label


【解决方案1】:

您非常接近 - image 参数只需要一个空字符串而不是 None。

def clear_label_image():
    brand_preview.config(image='')

【讨论】:

  • 谢谢,如果按钮必须删除它,但不知何故,如果我在它之后添加新图像,旧图像又在那里,那很奇怪!
  • 什么意思,旧的还在吗?
  • 如果按钮首先必须清理标签然后给它一个新的图像,那么旧的会回来/仍然存在。总而言之,我试图创建一个预览窗口。我们有 2 个按钮可以做同样的事情,清洁标签并在标签的顶部或底部显示图像。如果我单击此按钮,它必须删除顶部图像并使用新的(机器人图像)更新它。但我想我一个人可以解决,你已经帮了我很多。
  • 标签中应该只有 0 或 1 张图片。我没有看到与您所描述的行为类似的情况。
  • 好吧,这可能是我的问题,所有代码都很长,所以我试图只发布相关部分,但我可能不得不使用 Canvas。 Atm 我在标签上绘制了另一个标签,所以我在主标签的顶部有主标签 + 小标签。我使用此按钮更新小标签中的图像,因此它们显示在主标签的底部或顶部。
【解决方案2】:

经过一番谷歌搜索,我找到了这个解决方案

def clear_label_image():
    #brand_preview.config(image = None)
    brand_preview.image.blank()
    brand_preview.image = None

这肯定会清除按钮上的图像。我还没有尝试更改为新图像。

我刚刚从网上复制了它,它确实有效。我用

创建了图像
photoimg_brand = tk.PhotoImage(file='/usr/share/httpd/icons/world1.gif')

我用 python 2.7 做了这个,我唯一的导入是import Tkinter as tk

【讨论】:

  • 空白从何而来?它是一个未知的属性
  • @RomanDammer 我更新了我的答案,但很抱歉我没有很好的信息给你。我看到您使用 ImageTk 创建 PhotoImage。这可能就是区别。
【解决方案3】:

如果您使用label 显示图像,那么您可以这样做:

label.pack_forget()

label 应该是全局的

【讨论】:

  • 嗨 katt,欢迎来到 Stack Overflow。请使用正确的英语。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多