有什么方法可以从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

最佳答案

因为tkintertk的包装,所以PhotoImage同样是以image的包装。很明显,您不能只是从该PhotoImage向后移动并创建一个image

但是,由于您可以执行tk命令,并且PhotoImageimage具有相似的结构,因此最好的选择是:

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

foo = root.call(label.cget('image'), 'cget', '-file')
bar = image2['file']
print('1st image:\t%s\n2nd image:\t%s\nEqual:\t%r' % (foo, bar, foo == bar))



tk image
tk photo

08-24 19:39