5

如何访问PhotoImage()类对象的宽度和高度信息?我试过PhotoImage(...).winfo_width()PhotoImage(...)["Width"]。他们两个都没有工作。

4

3 回答 3

8

PhotoImage 对象有一个widthandheight方法:

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()
于 2016-03-16T02:08:06.487 回答
2

这可能是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
于 2016-03-16T02:06:48.097 回答
1

尝试:

In [32]: tk_img = tk.PhotoImage(file='./pixel-art-2237058.gif')
于 2017-09-06T06:15:12.683 回答