当我尝试添加文件对话框按钮时,我不断收到如下错误:
_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()
我对您的代码进行了一些修改,使您能够将图像加载到根窗口图标中。
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")
根据您的错误,问题出在您的文件格式上,请将 tkinter 窗口图标格式更改为
.ico
。图标只能是 .ico
格式。
删除此
from file_dialog import filedialog
导入,您已经从 tkinter 导入了 filedialog。
将您的应用程序窗口更改为
TopLevel()
窗口。您可以了解更多关于他们的信息这里
在调用
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()