【问题标题】:How do I use the base64 encoded image string in Tkinter label?如何在 Tkinter 标签中使用 base64 编码的图像字符串?
【发布时间】:2017-06-29 17:20:42
【问题描述】:

我正在编写一个使用一些 JPG 文件作为其背景的 tkinter 程序。但是,我发现当使用“pyinstaller”将脚本转换为 .exe 文件时,用于 tkinter 窗口的图像不会被编译/添加到 .exe 文件中。

因此,我决定在 Python 脚本中对图像进行硬编码,这样就没有外部依赖。为此,我做了以下几件事:

import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)

以上代码用于解码base 64编码的Image数据。 我想将此解码后的图像数据用作图片并在 tkinter 中显示为标签/按钮。

例如:

from tkinter import *
root=Tk()
l=Label(root,image=image=PhotoImage(data=datas)).pack()
root.mainloop()

但是,tkinter 不接受将存储在data 中的值用作图像。 它显示以下错误 -

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    l=Label(root,image=PhotoImage(data=datas))
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3394, in __init__

    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3350, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize image data

【问题讨论】:

  • 你用的是python2还是python3?根据这个question,python3 似乎是可能的。
  • @j_4321 我正在使用 Python 3。我已经检查了这个问题,但它似乎没有解决我的问题。
  • 那么你试过question中给出的代码了吗?
  • @j_4321 是的,我试过了,但没有帮助。
  • 除了base64编码技术之外,有没有其他方法可以将图像嵌入到python脚本中,以便可以在tkinter GUI中使用?

标签: python image tkinter base64 pyinstaller


【解决方案1】:

Tkinter PhotoImage 类(在带有 tk 8.6 的 Python 3 中)只能读取 GIF、PGM/PPM 和 PNG 图像格式。读取图片有两种方式:

  • 来自文件:PhotoImage(file="path/to/image.png")
  • 来自 base64 编码的字符串:PhotoImage(data=image_data_base64_encoded_string)

首先,如果要将图像转换为base64编码的字符串:

import base64

with open("path/to/image.png", "rb") as image_file:
    image_data_base64_encoded_string = base64.b64encode(image_file.read()) 

然后在 Tkinter 中使用它:

import tkinter as tk

root = tk.Tk()

im = tk.PhotoImage(data=image_data_base64_encoded_string)

tk.Label(root, image=im).pack()

root.mainloop()

我认为您的问题是您在使用PhotoImage 之前使用datas= base64.b64decode(base64_encodedString) 解码了字符串,而您应该直接使用base64_encodedString

【讨论】:

  • 确实如你所料错误,我使用解码后的值来创建图像对象。谢谢!
【解决方案2】:

为了纠正 j_4321 的非常好的答案,PhotoImage 的正确行是:

im = tk.PhotoImage(data=image_data_base64_encoded_string)

以及我编写“图像”字符串以便在之后导入它的解决方案:

with open("image.py", "wb") as fichier:
    fichier.write(b'imageData=b\'' + image_data_base64_encoded_string + b'\'')

一个简单的import image as img,图像数据将通过 Pyinstaller 存储在 .exe 文件中(-F 选项)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多