首页 > 解决方案 > Python 3.6 的成像问题

问题描述

我正在创建人工智能来使用 Python 玩中国跳棋,但我什至无法显示棋盘的图像!

我正在使用这段代码:

from tkinter import *
root = Tk()
board = PhotoImage(file="board.ppm")
root.mainloop()

我收到以下错误:

Traceback (most recent call last):
  File "/Users/GAMEKNIGHT7/Desktop/genius hour/chineseCheckersAI(genius hour).py", line 3, in <module>
    board = PhotoImage(file="board.ppm")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "board.ppm"

我将代码文件放在与图像相同的文件中。发生了什么?我该如何解决?

标签: pythonimage

解决方案


尝试在终端中运行以下命令:

file board.ppm

如果它里面有这个词ASCII,那意味着你的图像是未压缩的 ASCII(NetPBM type=3),Tkinter不会喜欢它:

board.ppm: Netpbm image data, size = 10 x 10, pixmap, ASCII text

如果您的文件正确,它将报告rawbitsNetPBM type=6):

board.ppm: Netpbm image data, size = 10 x 10, rawbits, pixmap

如果你想从 ASCII/P3 转换为 binary/rawbits/P6,你可以像这样用homebrew安装ImageMagick

brew install imagemagick

然后像这样转换:

convert board.ppm -compress lossless board.ppm

推荐阅读