如何在Tkinter标签中使用base64编码的图像字符串?

2024-05-19 08:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

上述代码用于解码base64编码的图像数据。 我想用这个解码后的图像数据作为图片,并在tkinter中显示为标签/按钮。在

例如:

^{pr2}$

但是,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

Tags: 文件inpy图像image脚本编码data
2条回答

为了纠正ju 4321的正确答案,PhotoImage的正确行是:

im = tk.PhotoImage(data=image_data_base64_encoded_string)

以及我的解决方案,即写入“image”字符串以便在以下时间后导入它:

^{2}$

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

TkinterPhotoImage类(在Python3和TK8.6中)只能读取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中使用它:

^{2}$

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

相关问题 更多 >

    热门问题