有没有办法从 tkinter.Label
实例中获取 tkinter.PhotoImage
对象?我知道有 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
字符串中获取图像对象? IE。一个从 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()
return image_hash == expected_hash
最佳答案
tkinter
是 tk
的包装器,PhotoImage
也是 image
的包装器.很明显,您不能只是向后移动并从那个 image
创建一个 PhotoImage
。
但是,因为您可以执行 tk 命令并且 PhotoImage
和 image
都具有相似的结构,所以您最好的选择是这样的:
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))
关于python - 从 tkinter 标签获取 PhotoImage 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47692877/