【发布时间】:2012-08-19 23:52:44
【问题描述】:
这是我的第一个 Python 脚本/程序,所以我用谷歌搜索了所有内容并开始掌握一点。
我正在尝试制作一个随机选择目录中的图片并将其显示为标签的程序。
除了一件事,一切都很顺利。我已将随机图片作为变量,并尝试告诉 Image.open 使用变量中的路径。问题是 Image.open 不将变量识别为文件名/路径,而是将其识别为
"PIL.PngImagePlugin.PngImageFile image mode=P size=980x93 at 0xF185A8".
我已经用谷歌搜索了一整夜,但找不到答案或解决方案。如果我同时打印img1-variable 和path1-variable,它就会正确。
有人知道如何解决这个问题吗?我将非常感谢任何答案! 我有 Python 2.7.3
这是我的脚本(未完成)。
#! /usr/bin/env python
from Tkinter import *
import Tkinter
import random
from PIL import Image, ImageTk
import os
root = Tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" %(w, h))
root.configure(background="darkgreen")
dir = 'decks/'
img1 = random.choice(os.listdir(dir))
path1 = dir+img1
card1 = Image.open(path1)
card1 = card1.resize((140, 190), Image.ANTIALIAS)
magicback = Image.open("datapics/magicback.jpg")
magicback = magicback.resize((140, 190), Image.ANTIALIAS)
magicbutton = ImageTk.PhotoImage(magicback)
label = Label(root, image=magicbutton)
label.image = magicbutton
label.place(x=1, y=20)
label1 = Label(root, image=card1)
label1.image = card1
label1.place(x=1, y=230)
label2 = Label(root, image=magicbutton)
label2.image = magicbutton
label2.place(x=151, y =230)
label3 = Label(root, image=magicbutton)
label3.image = magicbutton
label3.place(x=301, y=230)
label4 = Label(root, image=magicbutton)
label4.image = magicbutton
label4.place(x=451, y=230)
label5 = Label(root, image=magicbutton)
label5.image = magicbutton
label5.place(x=601, y=230)
label6 = Label(root, image=magicbutton)
label6.image = magicbutton
label6.place(x=751, y=230)
label7 = Label(root, image=magicbutton)
label7.image = magicbutton
label7.place(x=901, y=230)
root.mainloop(0)
【问题讨论】:
-
"Image.open 无法识别变量" 证明一下。
-
另外,您可以删除
label1.*之后的大部分代码,以便提出问题(例如ssccse)。如果您打印出path1,然后复制此字符串,然后使用PIL交互式地尝试打开并显示带有粘贴字符串的图像,这样可以吗?跨度> -
嗨!我不明白你关于证明的评论?该脚本给出的错误是 image.open() 中不存在“PIL.PngImagePlugin.PngImageFile 图像模式=P size=980x93 at 0xF185A8”。是的,很抱歉 label1 之后的代码。我不确定你对最后一部分的意思是什么,你的意思是硬编码路径?
-
@user1610593 是的,这是一种解决问题的方法。显示图像的生成路径,将其复制,然后将其粘贴到命令中,按原样打开/显示文件。 (您正在复制/粘贴以便生成 exact 字符串)-此外,该目录中除了图像文件之外没有其他文件吗?
-
错误信息表明
open实际上没有接收到字符串。我不相信这里显示的代码是实际生成该消息的代码。
标签: python variables random tkinter python-imaging-library