为什么我不能在tkinter Toplevel()窗口中显示图像? [英] Why can't I display an Image in a tkinter Toplevel() window?

查看:98
本文介绍了为什么我不能在tkinter Toplevel()窗口中显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个python程序tkinter,按下按钮后,它将打开一个新的全屏tkinter窗口,其中包含图像并播放音频文件-这是我的代码:

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

(我的图像和音频文件都和我的python文件一起放在桌面上)

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

但是,当我运行代码时,当我按下按钮时,音频会播放,但不会打开第二个tkinter窗口.

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

我试图销毁()buttonWindow,并尝试了许多不同的方式在tkinter窗口中包括图像-如果我使用PhotoImage()删除代码行,则该窗口出现(显然,我得到了一种语法错误,指出未定义'img'.

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

我该如何解决?

谢谢,路易斯

推荐答案

您的playound()命令阻止执行.playound()命令具有一个可选字段"block",默认情况下为True.将其更改为False将继续执行并允许mainloop()继续.

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.

第二,只需调用label.draw()将图像绘制到TopLevel窗口即可.

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

这是代码:

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

干杯!

这篇关于为什么我不能在tkinter Toplevel()窗口中显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆