【问题标题】:Images not appearing in a tkinter window and button图像未出现在 tkinter 窗口和按钮中
【发布时间】:2019-03-17 16:00:30
【问题描述】:

当我尝试运行下面的程序时,它显示了这个错误:

程序:

import tkinter as tk

class RootWindow() :

    def __init__(self) :
        root=tk.Tk()
        self.root=root
        root.title("Isekai no yusha")
        root.wm_iconbitmap(bitmap = "Icon.xbm")
        root.configure(bg="black")
        root.resizable(width=False, height=False)

        screenWidth, screenHeight=root.winfo_screenwidth(), root.winfo_screenheight()
        screenWidth, screenHeight=int(screenWidth/2)-400, int(screenHeight/2)-200
        self.screenWidth, self.screenHeight=screenWidth, screenHeight

        #RootWindow.StartMenu(self)

        rootSize=(f"800x400+{screenWidth}+{screenHeight}")
        root.geometry(rootSize)
        root.mainloop()

    #def StartMenu(self) :
    #   newGameButton=tk.Button(self.root, bitmap=("new_game_icon.xbm"), bg="black", fg="white", border=False, command=self.root.destroy)
    #    newGameButton.pack()
    #    newGameButton.place(x=10, y=10)

master=RootWindow()

错误:

Exception has occurred: _tkinter.TclError
bitmap "new_game_icon.xbm" not defined
  File "D:\programmation\IDLE RPG\Test2.py", line 24, in StartMenu
    newGameButton=tk.Button(self.root, bitmap=("new_game_icon.xbm"), bg="black", fg="white", border=False, command=self.root.destroy)
  File "D:\programmation\IDLE RPG\Test2.py", line 17, in __init__
    RootWindow.StartMenu(self)
  File "D:\programmation\IDLE RPG\Test2.py", line 28, in <module>
    master=RootWindow()

我已经尝试将文件格式更改为 png、bmp 和 xbm,但它们都不起作用(文件已经在工作文件夹中,我已经检查了文件之间的名称和代码中的名称是否匹配) . 此外,当我尝试在没有 Button 的情况下运行程序时,窗口左上角的图标没有显示,我得到的是文件的图像。 (下面的屏幕截图)。

窗口图标:

Window icon

使用的IDE:Visual Code Studio,操作系统:Windows 10

对不起,我语言不好,我是法国学生。

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    如果我明白你想要做什么。

    import tkinter as tk
    
    class RootWindow() :
    
        def __init__(self) :
            root=tk.Tk()
            self.root=root
            root.title("Isekai no yusha")
    
            imgicon = tk.PhotoImage(file='icon.png')
            root.call('wm', 'iconphoto', root._w, '-default', imgicon)   
            #root.wm_iconbitmap(bitmap = "Icon.xbm")
    

    【讨论】:

    • 谢谢,现在它适用于您的更改,但小部件按钮的位图一直存在问题,我是否需要像您一样做,但将其应用于按钮?跨度>
    • 你指的是 wath 按钮吗?
    • 对不起,我指的是这个按钮,见下文:
    • #def StartMenu(self) : # newGameButton=tk.Button(self.root, bitmap=("new_game_icon.xbm"), bg="black", fg="white", border=错误,command=self.root.destroy) # newGameButton.pack() # newGameButton.place(x=10, y=10)
    • @CiurteSergiu:“小部件按钮的位图问题”:是的。另请阅读Why does Tkinter image not show up if created in a function?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多