Reputation: 337
How do I access the width and height information on a PhotoImage()
class object?
I tried PhotoImage(...).winfo_width()
and PhotoImage(...)["Width"]
. Both of them didn't work.
Upvotes: 4
Views: 25504
Reputation: 385900
The PhotoImage objects have a width
and height
method:
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()
Upvotes: 9
Reputation: 119
It's possibly tkinter
bug. Better use PIL
/Pillow
Image
and ImageTk.PhotoImage
instead of just 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
Upvotes: 2