【问题标题】:Importing image into Tkinter - Python 3.5将图像导入 Tkinter - Python 3.5
【发布时间】:2016-10-08 14:57:14
【问题描述】:

我在为 Python 3.5 将图像导入 Tkinter 时遇到了很大的困难,这是针对我的 A2 项目的,并且在 的所有方法中都遇到了困难>将 .JPG 文件导入我的窗口。下面是我的另一个窗口的 GUI 层,基于我发现但根本没有工作的另一个线程。任何帮助表示赞赏。

import tkinter 
from tkinter import *

root=Tk()
root.geometry('1000x700')
root.resizable(False, False)
root.title("Skyrim: After Alduin")

photo = PhotoImage(file="Skyrim_Map")
map=Label(root, image=photo)
map.photo=photo
map.pack()

root.mainloop()

这是我收到的错误:

Traceback (most recent call last):
  File "E:\Programming\Text_Adventure_Project\GUI_Interface-S_AA.py", line 14, in <module>
    photo = PhotoImage(file="Skyrim_Map")
  File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3393, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3349, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "Skyrim_Map": no such file or directory

【问题讨论】:

  • 图片通常有扩展名。尝试添加它。并确保它与脚本在同一目录中或使用绝对路径。
  • 放入扩展,并尝试了一条绝对路径。同样的错误。
  • 你真的有一个没有后缀的文件Skyrim_Map吗? Python 绝对不会说“没有这样的文件或目录”,除非这是真的。
  • 不,它的末尾有一个.jpg,只是我放在这里的副本中没有。
  • 一个 MCVE (stackoverflow.com/help/mcve) 可能是 open("Skyrim_Map", 'rb')。如果是这样,忘记 tkinter 并在这个简单的语句中编辑路径,直到它工作。此外,剪切并粘贴您运行的实际代码。如果您知道贴出的代码不一样,请更正。

标签: python image import tkinter tk


【解决方案1】:

首先检查路径,如果正确的路径仍然存在错误“没有这样的文件或目录”,请编辑并放置最新版本的代码。 如果错误是“无法识别图像文件中的数据”,您可以使用 PIL 进行更正

 [...]
 from PIL import ImageTk

 [...]
 photo = ImageTk.PhotoImage(file='Skyrim_Map.jpg')
 [...]

【讨论】:

    【解决方案2】:

    试试这个:

    from PIL import Image , ImageTk img = Image.open("your_img") image = ImageTk.PhotoImage(img)

    【讨论】:

      【解决方案3】:

      另一种观点:

      类应用:

          ...
          self.photo=PhotoImage(file='picture.gif')
          self.item=self.can.create_image(200, 100, image=self.photo)
          ...
      

      希望有所帮助! ;)

      【讨论】:

      • 这仅适用于少数图像格式,例如 .gif.png 不包括 OP 实际询问的 .jpg
      • 使用 Gimp 将 .jpg 转换为 .gif 并通过右键单击图像并选择 Image Resize 来调整大小;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2016-06-02
      • 2016-03-19
      • 1970-01-01
      • 2014-07-17
      相关资源
      最近更新 更多