PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

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

 July 30, 2022     image, python, tk, tkinter     No comments   

Issue

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


Solution

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!



Answered By - Nic Thibodeaux
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing