我一直在开发一个小程序,将PNG、JPG和JPEG文件转换为.ICO文件。这相对来说比较简单,但当我试图使用PIL的ImageTk在Tkinter中显示选定的PNG图像时,我遇到了一个奇怪的错误
from tkinter import *
from tkinter import filedialog
import re
from PIL import Image, ImageTk
root = Tk()
pathToImage = ''
selectedImage = ''
def make_square(im, min_size=256, fill_color = (0, 0, 0)): # Puts the selected image into a black square
x, y = im.size
size = max(min_size, x, y)
new_im = Image.new('RGB', (size,size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
return new_im
def select_image(): # Function that is run when Select PNG button is clicked
global pathToImage
pathToImage = filedialog.askopenfilename(filetypes=[('PNG Files','*.png'),('JPG Files','*.jpg'),('JPEG Files','*.jpeg')]) # Gets path to PNG, JPG or JPEG image
image = Image.open(pathToImage) # Opens image in PIL
image = make_square(im=image) # Turns image into square for ICO conversion
#!!!!!!!!!!!!!!!!!!!!! ERROR Among these 3 lines
global selectedImage # Here I try to tell Python I'm referring to the global variable selectedImage
selectedImage = (ImageTk.PhotoImage(image=pathToImage)) # selectedImage is given the value of ImageTk.PhotoImage with the source image being the path of the selected image
Label(root, image=selectedImage).pack() # Throws an error for some reason
# Rest of the code works fine
image.save('output.ico')
Label(root,text='Converted file stored in the same folder as \'PNG to ICO.py\'').pack()
Button(root,text='Select PNG', command=select_image).pack()
root.mainloop()
我尝试将图像保存为变量显示,但这似乎也不起作用。谁能帮我指出我做错了什么?我真的很感激
您的代码有几个问题
在您的
(ImageTk.PhotoImage(image=pathToImage))
行中,您正在传递一个路径(str
),该路径不是它应该采用的路径,ImageTk.PhotoImage
以Image(path)
为例。因此,将其更改为make_square
函数返回的图像每次单击按钮时,它都会创建一个新的
label
如果这是您想要的,则忽略此项,如果不是,则在创建Button
后在函数外创建标签,然后在函数中更新标签。我真的不明白你为什么要使用
global
当你可以实现你的目标而不需要变量pathToImage
或selectedImage
除非你想在程序中访问这个图像以下是代码的改进版本
相关问题 更多 >
编程相关推荐