Search code examples
pythonimagefor-looptkinterttk

Python-Tkinter, for-loop to create pictured button


I'm still quiet new to programming, so maybe my question in pretty easy or even stupid. As said in the title I'm trying to programm a for loop, which creates a pictured button widget for each picuture in a certain folder. This is what I have so far:

import tkinter  
from tkinter import ttk
from tkinter import PhotoImage
import os

root = tkinter.Tk()

list_files = os.listdir(".")

for file in list_files:
    if file.endswith(".gif"):
        drink = PhotoImage(file)
        print(drink)
        b1 = ttk.Button(image=drink, text="Hello", compound="right").pack()
        l1 = ttk.Label(image=drink).pack()


root.mainloop()

Now what I get is two widgets, one label displaying nothing and a button displaying Hello. In the shell it says drink1.gif, which is correct, because that's the only gif file in my standard python folder...

what have I done wrong?


Solution

    1. Use PhotoImage(file='path_to_file') to create image from path.
    2. When PhotoImage object is garbage-collected by Python, the label is cleared. You must save reference to drink object somewhere: l1.image = drink:
      http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
    3. widget.pack() method return nothing.

    import tkinter  
    from tkinter import ttk
    from tkinter import PhotoImage
    import os
    
    root = tkinter.Tk()
    list_files = os.listdir(".")
    for path in list_files:
        if path.endswith(".gif"):
            drink = PhotoImage(file=path)
            b1 = ttk.Button(root, image=drink, text="Hello", compound="right")
            b1.pack()
            l1 = ttk.Label(root, image=drink)
            l1.image = drink
            l1.pack()
    
    root.mainloop()