【问题标题】:Image.open can't handle random selected image-variable PythonImage.open 无法处理随机选择的图像变量 Python
【发布时间】:2012-08-19 23:52:44
【问题描述】:

这是我的第一个 Python 脚本/程序,所以我用谷歌搜索了所有内容并开始掌握一点。

我正在尝试制作一个随机选择目录中的图片并将其显示为标签的程序。

除了一件事,一切都很顺利。我已将随机图片作为变量,并尝试告诉 Image.open 使用变量中的路径。问题是 Image.open 不将变量识别为文件名/路径,而是将其识别为

"PIL.PngImagePlugin.PngImageFile image mode=P size=980x93 at 0xF185A8".

我已经用谷歌搜索了一整夜,但找不到答案或解决方案。如果我同时打印img1-variablepath1-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


【解决方案1】:

如果我正确理解了这个问题,您的问题是image.open(),我认为问题在于您将目录和文件名连接在一起时将它们视为字符串:

path1 = dir + img1

您应该尝试使用os.path 模块将两者结合起来:

path1 = os.path.join(dir, img1)

【讨论】:

  • 虽然使用os.path.join() 是一般字符串操作的好习惯,但我认为它在这里没有什么不同
  • 嗨!感谢您的回答。是的,它的 image.open() 就是问题所在。我需要它来使用 dir/ + 随机选择的文件(例如图像),但 image.open 出于某种原因而不是路径获取图像的属性。我已经尝试过 os.path.join 但没有区别 =/
猜你喜欢
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多