以下程序适用于目录中的第一个.jpg。 第二次调用时,它会收到一个“ _tkinter.TclError:图像 ““ pyimage2”不存在”异常。为什么会出现错误? 有没有办法重用第一张图片而不是创建第二张图片?
导入sys,os
如果sys.version_info [0] == 2:
进口Tkinter
tkinter = Tkinter
其他:
导入tkinter
从PIL导入ImageTk
def showPIL(pilImage):
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
imgWidth, imgHeight = pilImage.size
# resize photo to full screen
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
print(image)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.mainloop()
names = os.listdir("E://Users//scott//Pictures")
print(names)
for file in names:
print(file)
if file[-4:] == ".jpg":
file=Image.open("E://Users//scott//Pictures//"+file)
showPIL(file)
这是控制台输出。追溯(最近一次通话):文件 “ e:\ Users \ scott \ Documents \ Python \ image test.py”,第36行,在 showPIL(file)在showPIL中的第27行,文件“ e:\ Users \ scott \ Documents \ Python \ image test.py” imagesprite = canvas.create_image(w / 2,h / 2,image = image)文件“ C:\ Program Files \ Python37 \ lib \ tkinter__init __。py”,第2486行,在 create_image 返回self._create('image',args,kw)文件_create中的文件“ C:\ Program Files \ Python37 \ lib \ tkinter__init __。py”,行2477 *(参数+ self._options(cnf,kw)))) _tkinter.TclError:图像“ pyimage2”不存在
>
答案 0 :(得分:1)
搜索后,我发现第一个问题tkinter.Tk()被多次调用,而必须调用 只有一次,所以我将其从showPIL函数移到了 初始化。下一个问题是mainloop阻塞,所以我 用root.update_idletasks()和 root.update()。以下是我期望和需要的作品:
import sys, os
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
def showPIL(pilImage):
imgWidth, imgHeight = pilImage.size
# resize photo to full screen
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.update_idletasks()
root.update()
# root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
names = os.listdir("E://Users//scott//Pictures")
print(names)
for file in names:
print(file)
if file[-4:] == ".jpg":
file=Image.open("E://Users//scott//Pictures//"+file)
showPIL(file)
time.sleep(5)