簡體   English   中英

在Python中使用PhotoImage在Tkinter中顯示圖像

[英]Using PhotoImage to display an image in Tkinter in Python

我正在嘗試創建一個具有主菜單和設置菜單的應用程序。 我想為每個背景設置背景。 但是我從設置菜單開始。 我收到一條錯誤消息: _tkinter.TclError: image "pyimage1" doesn't exist 我究竟做錯了什么?

from tkinter import *
from tkinter.ttk import *

install_directory = '...'


# ***********************************MAIN MENU*****************************************************
def root():

    # ~~~Defines window~~~
    main_window = Tk()
    main_window.iconbitmap(install_directory + r'\resources\icons\logo.ico')  # Changes the icon for window
    main_window.title('Auto Transfer')  # Changes window name
    main_window.geometry("300x200")

    # ~~Adds a background~~~
    background = PhotoImage(file=install_directory + r'\resources\backgrounds\stardust.gif')
    label = Label(main_window, image=background)
    label.pack()

    # ~~~Menu Bar~~~
    menubar = Menu(main_window)  # Creates the menu bar

    # ~~~File menu~~~
    filemenu = Menu(menubar, tearoff=0)
    filemenu.add_command(label="Quit", command=lambda: main_window.destroy())  # Exits the program

    # ~~~Settings menu~~~
    settingsmenu = Menu(menubar, tearoff=0)
    settingsmenu.add_command(label="Change settings...", command=lambda: options(main_window))

    # ~~~Add menus to bar~~~
    menubar.add_cascade(label='File', menu=filemenu)
    menubar.add_cascade(label='Settings', menu=settingsmenu)

    # ~~Adds menu bar to the screen~~~
    main_window.config(menu=menubar)

    # ~~Adds 'RUN' button~~


    # ~~~Runs window~~~
    main_window.mainloop()


# *********************************OPTIONS MENU****************************************************
def options(main_window):

    options_window = Toplevel()
    options_window.iconbitmap(install_directory + r'\resources\icons\logo.ico')  # Changes the icon for window
    options_window.title('Settings')  # Changes window name
    options_window.geometry("720x480")

    # ~~Adds a background~~~
    background = PhotoImage(file=install_directory + r'\resources\backgrounds\stardust.gif')
    label = Label(options_window, image=background)
    label.pack()




# *******************************RUN APP**************************************************************
if __name__ == '__main__':
    root()

我認為原因是您在代碼中使用了兩個Tk()實例。 這不是很好。 一個tkinter應用程序應該只有一個主循環(即一個實例Tk())。 要制作其他窗口,請使用TopLevel小部件。

在您的選項函數中使用此函數,而不要創建新的Tk():

 options_window = Toplevel()

希望這可以幫助。 還要確保圖像文件路徑正確。

暫無
暫無

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

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