1

当我尝试添加文件对话框按钮时,我不断收到如下错误:

_tkinter.TclError: can't use "pyimage1" as iconphoto: not a photo image

这是我的代码:

from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from file_dialog import filedialog

root = Tk()
img = PhotoImage(file='icon.png')

root.geometry("700x500") # the application window size
root.iconphoto(False,img) #application icon
root.title("I need a NAME!") # title of window

def file_dialog():
    root.filename = filedialog.askopenfilename(initialdir="Downloads", title="Select A File To Start", filetypes=(("mp4 files", "*.mp4"),("mov files", "*.mov"),("png files", "*.png"),("jpeg files", "*.jpeg"),("jpg files", "*.jpg")))


def file_dialog_button(app):
    app = app.tk()
    button = app.Button(app, text="Start!", command=file_dialog)
    button.pack(app)

root.mainloop()

print("Succesful Build")

file_dialog()
file_dialog_button()
4

2 回答 2

1

我对您的代码进行了一些修改,使您能够将图像加载到根窗口图标中。

from tkinter import *是一种不好的做法,因此我已将其更改为import tkinter as tk并进行了必要的更改。

问题是您试图在声明函数和变量之前引用它们。

import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog

root = tk.Tk()
root.geometry("700x500") # the application window size
root.title("I need a NAME!") # title of window

def file_dialog():
    filename = filedialog.askopenfilename(
        initialdir="Downloads",
        title="Select A File To Start",
        filetypes=(
            ("mp4 files", "*.mp4"),
            ("mov files", "*.mov"),
            ("png files", "*.png"),
            ("jpeg files", "*.jpeg"),
            ("jpg files", "*.jpg")))

    if filename:
        root.img = tk.PhotoImage(file=filename)
        root.iconphoto( False, root.img ) # application icon

app = tk.Toplevel(root)
app.transient( root )
button = tk.Button(app, text="Start!", command=file_dialog)
button.pack(fill = "both", expand = True)

root.mainloop()

print("Successful Build")
于 2021-08-12T03:57:50.503 回答
0
  1. 根据您的错误,问题出在您的文件格式上,将您的 tkinter 窗口图标格式更改为.ico. 图标只能是.ico格式。

  2. 删除这个from file_dialog import filedialog导入,你已经从 tkinter 导入了 filedialog。

  3. 将您的应用程序窗口更改为TopLevel()窗口。您可以在此处了解有关它们的更多信息

  4. 在您的电话中,file_dialog_button()您没有传递变量的值app

您的最终代码应如下所示:

from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog

root = Tk()
img = PhotoImage(file='icon.ico')

root.geometry("700x500") # the application window size
root.iconphoto(False,img) #application icon
root.title("I need a NAME!") # title of window

def file_dialog():
    filename = filedialog.askopenfilename(initialdir="Downloads", title="Select A File To Start", filetypes=(("mp4 files", "*.mp4"),("mov files", "*.mov"),("png files", "*.png"),("jpeg files", "*.jpeg"),("jpg files", "*.jpg")))


def file_dialog_button(app):
    app = Toplevel()
    button = Button(app, text="Start!", command=file_dialog)
    button.pack(app)

print("Succesful Build")

file_dialog()
file_dialog_button('exmaple_name')
root.mainloop()
于 2021-08-12T03:45:44.340 回答