【问题标题】:Opening another window by a button and returning an empty window using Tkinter, Python通过按钮打开另一个窗口并使用 Tkinter,Python 返回一个空窗口
【发布时间】:2020-10-14 20:06:32
【问题描述】:

当通过单击另一个Button 打开另一个窗口时,grid() 无法绘制Button,只返回一个空窗口和一个错误:

_tkinter.TclError: image "pyimage1" doesn't exist

我在另一个主题 (here) 中看到了类似的问题,但它发生在 Label 上,使用 .draw () 解决了这个问题。我想知道当小部件是Button 时是否有类似的解决方案。
PS:我确定我从我的项目文件夹中正确放置了图像路径.运行程序时,第一个按钮可以显示相同的图像。

from tkinter import *
import pygame

root = Tk()
root.title('Test')

def open_window():
    other_window = Tk()

    def play_sound():
        pygame.init()
        pygame.mixer.music.load('path.mp3')
        pygame.mixer.music.play()
        pygame.event.wait()

    bt_play_sound = Button(other_window, text = 'Play', image=img_play, command = play_sound, compound="top")
    bt_play_sound.grid(row = 0, column = 0)

    other_window.mainloop()

#IMAGES
img_play = PhotoImage(file="path.png")

open_other_window = Button(root, text = "Open", image=img_play, command = open_window, compound="top")
open_other_window.grid(row = 0, column = 0)

root.mainloop()

【问题讨论】:

  • 不建议使用多个Tk() 将子窗口替换为Toplevel()

标签: python button tkinter pygame mp3


【解决方案1】:

要使第二个图像正常工作,您需要创建一个新的 PhotoImage 并将 master 选项设置为第二个 Tk 窗口。

def open_window():
    other_window = Tk()

    def play_sound():
        pygame.init()
        pygame.mixer.music.load('path.mp3')
        pygame.mixer.music.play()
        pygame.event.wait()
        
    img_play = PhotoImage(file="path.png", master=other_window)    # <<<< Add this line
    bt_play_sound = Button(other_window, text = 'Play', image=img_play, command = play_sound, compound="top")
    bt_play_sound.grid(row = 0, column = 0)
    
    other_window.mainloop()

附带说明,tkinter 将图像存储为字符串(就像字典中的键)。 img_play = "pyimage1" (或任何 tkinter 分配的字符串)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-11
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2021-12-03
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多