从tkinter标签获取PhotoImage对象

时间:2017-12-07 10:27:25

标签: python image user-interface tkinter

有没有办法从tkinter.PhotoImage实例获取tkinter.Label对象?我知道有this question,它有一个部分令人满意的答案,但我真的需要得到一个PhotoImage对象:

>>> import tkinter as tk
>>>
>>> root = tk.Tk()
>>>
>>> image1 = tk.PhotoImage(file="img.gif")
>>> image2 = tk.PhotoImage(file="img.gif")
>>>
>>> label = tk.Label(root, image=image1)
>>> label._image_ref = image1
>>> label.cget("image") == image2
False

是否有一个允许我从pyimage字符串中获取图像对象的函数?即一个从label.cget("image")获得?

答案是apparantly,你做不到。你可以得到的最接近的是获取图像源(文件或数据)并检查(可能是通过散列)这两个图像是否相同。 tkinter.PhotoImage 实现__eq__,因此您无法仅比较两个图像以获得相同的数据。这是一个解决问题的最后一个例子(主要是):

import hashlib
import os
import tkinter as tk

_BUFFER_SIZE = 65536


def _read_buffered(filename):
    """Read bytes from a file, in chunks.
    Arguments:
    - filename: str: The name of the file to read from.
    Returns:
    - bytes: The file's contents.
    """
    contents = []
    with open(filename, "rb") as fd:
        while True:
            chunk = fd.read(_BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
        return bytes().join(contents)


def displays_image(image_file, widget):
    """Check whether or not 'widget' displays 'image_file'.
    Reading an entire image from a file is computationally expensive!
    Note that this function will always return False if 'widget' is not mapped.
    This doesn't work for images that were initialized from bytes.
    Arguments:
    - image_file: str: The path to an image file.
    - widget: tk.Widget: A tkinter widget capable of displaying images.
    Returns:
    - bool: True if the image is being displayed, else False.
    """
    expected_hash = hashlib.sha256(_read_buffered(image_file)).hexdigest()
    if widget.winfo_ismapped():
        widget_file = widget.winfo_toplevel().call(
            widget.cget("image"), "cget", "-file"
        )
        if os.path.getsize(widget_file) != os.path.getsize(image_file):
            # Size differs, the contents can never be the same.
            return False
        image_hash = hashlib.sha256(
            _read_buffered(widget_file)
        ).hexdigest()
        if image_hash == expected_hash:
            return True
        return False

1 个答案:

答案 0 :(得分:1)

由于tkintertk的包装,因此PhotoImage同样是image的包装器。很明显,您不能向后移动并从{{​​1}}创建PhotoImage

但是,因为你可以执行tk命令并且imagePhotoImage具有相似的结构,你最好的选择是这样的:

image