Search code examples
pythontkinterphotoimage

How to find out size of a PhotoImage in Tkinter?


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.


Solution

  • 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()