pythonimagetkinterimage-resizingttkwidgets

I want to add a button with a image using tkinter, but my img is too big. How can I resize it, but display it as a png?


I'm learning python and tkinter from scratch, by my own. I have this button:

info = tk.PhotoImage(file= "./assets/info.png")
boton_info = ttk.Button(f2, width=30, image= info)
boton_info.grid(row=2, column=3, sticky="nwe", padx=15)

I want to display a little info button. The img is 512x512 and it displays too big. How can I resize the img and display it inside the Button??

I've tried this alternative to resize the img:

info_g = Image.open("./assets/info.png")
info = info_g.resize((30,30), Image.LANCZOS)
boton_info = ttk.Button(f2, width=30, image=info)

But I get this error error


Solution

  • The image option of tk.Button expect tk.PhotoImage compatible image like the first example.

    However, in the second example, you used an instance of Image (from Pillow module) which is not compatible to tk.PhotoImage. You need to create the compatible image using ImageTk.PhotoImage class from Pillow module:

    info_g = Image.open("./assets/info.png")
    info = info_g.resize((30,30), Image.LANCZOS)
    tkimg = ImageTk.PhotoImage(info) # create PhotoImage compatible image
    boton_info = ttk.Button(f2, width=30, image=tkimg)