如何在 Tkinter 中找出 PhotoImage 的大小?

How to find out size of a PhotoImage in Tkinter?

如何访问 PhotoImage() class 对象的宽度和高度信息? 我尝试了 PhotoImage(...).winfo_width()PhotoImage(...)["Width"]。两个都不行。

这可能是 tkinter 错误。最好使用 PIL/Pillow ImageImageTk.PhotoImage 而不是 tk.PhotoImage

In [30]: import tkinter as tk
In [31]: from PIL import Image, ImageTk

In [32]: tk_img = tk.PhotoImage('./pixel-art-2237058.gif')
In [35]: tk_img.width()
Out[35]: 0

In [36]: pil_img = Image.open('./pixel-art-2237058.gif')
In [37]: tk_pil_img = ImageTk.PhotoImage(pil_img)
In [39]: tk_pil_img.width()
Out[39]: 811

PhotoImage 对象有一个 widthheight 方法:

import Tkinter as tk

image_data = '''
    R0lGODlhEAAQAMQZAMPDw+zs7L+/v8HBwcDAwLW1teLi4t7e3uDg4MLCwuHh4e7u7t/f38TExLa2
    tre3t7i4uL6+vu/v77q6uu3t7b29vby8vLm5ubu7u+3t7QAAAAAAAAAAAAAAAAAAAAAAACH5BAEA
    ABkALAAAAAAQABAAAAWNYCaOZFlWV6pWZlZhTQwAyYSdcGRZGGYNE8vo1RgYCD2BIkK43DKXRsQg
    oUQiFAkCI3iILgCLIEvJBiyQiOML6GElVcsFUllD25N3FQN51L81b2ULARN+dhcDFggSAT0BEgcQ
    FgUicgQVDHwQEwc+DxMjcgITfQ8Pk6AlfBEVrjuqJhMOtA4FBRctuiUhADs=
'''

root = tk.Tk()
image = tk.PhotoImage(data=image_data)
dimensions = "image size: %dx%d" % (image.width(), image.height())
label = tk.Label(root, compound="top", image=image, text=dimensions)
label.pack()
root.mainloop()

尝试:

In [32]: tk_img = tk.PhotoImage(file='./pixel-art-2237058.gif')