Why can't I display an Image in a tkinter Toplevel() window?

我与影子孤独终老i 提交于 2020-12-08 04:00:36

问题


I'm trying to create a python program tkinter that, upon the pressing of a button, opens a new full screen tkinter window containing an image and plays an audio file - here's my code:

from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound

def play():
    window = Toplevel()
    window.attributes('-fullscreen', True)
    img = ImageTk.PhotoImage(Image.open("pic.png"))
    label = Label(window, image=img).pack()
    playsound("song.mp3")
    
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()

(my image and audio file are both on the desktop with my python file)

However, when I run my code, when I press the button, the audio plays but no second tkinter window opens.

I've tried to destroy() the buttonWindow and have tried many different ways of including an image on a tkinter window - if I remove the line of code using PhotoImage(), the window appears (obviously I then get a syntax error stating that 'img' is not defined).

How could I solve this?

Thanks, Louis


回答1:


Your playsound() command is blocking execution. The playsound() command has an optional field 'block', which is True by default. Changing this to False will continue execution and allow mainloop() to continue.

Second, just call label.draw() to draw your image to the TopLevel window.

Here's the code:

from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound

def play():
    window = Toplevel()
    window.attributes('-fullscreen', True)
    img = ImageTk.PhotoImage(Image.open("pic.jpeg"))
    label = Label(window, image=img).pack()
    playsound("song.mp3",block=False)
    label.draw()
    
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()
buttonWindow.mainloop()

Cheers!



来源:https://stackoverflow.com/questions/62599709/why-cant-i-display-an-image-in-a-tkinter-toplevel-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!