문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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).

I believe you are supposed to run self.pack, according to the Zetcode tutorial.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top