Reputation: 101
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?
Upvotes: 2
Views: 2003
Reputation: 3205
PhotoImage(file='path_to_file')
to create image from path.PhotoImage
object is garbage-collected by Python, the label is cleared. You must save reference to drink
object somewhere: l1.image = drink
: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()
Upvotes: 3
Reputation: 13171
PhotoImage(file)
creates an image and gives it the name "drink1.gif", which is returned. If you actually want to load the file into the image, you need PhotoImage(file = file)
.
Upvotes: 2
Reputation: 10727
I believe you are supposed to run self.pack
, according to the Zetcode tutorial.
Upvotes: 0