簡體   English   中英

通過按鈕打開另一個窗口並使用 Tkinter、Python 返回一個空窗口

[英]Opening another window by a button and returning an empty window using Tkinter, Python

grid()不能繪制Button時,其他窗口點擊打開另一個Button ,只返回一個空的窗口和一個錯誤:

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

我在另一個主題( 這里)中讀到了一個類似的問題,但它發生在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()

要使第二個圖像工作,您需要創建一個新的 PhotoImage 並指定設置為第二個 Tk 窗口的master選項。

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 分配的字符串)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM