7

我有使用 PySimpleGUI 的 Python GUI,它需要显示多个我打算通过一组按钮导航的图。我知道我可以将所有绘图保存为给定文件夹中的 PNG,只需将它们加载到 Image 对象中,并在单击按钮时使用元素的 Update 方法来加载新图像。

像下面这样的东西效果很好:

[sg.Image(filename=os.getcwd() + pngFileName, key='key1', size=(5, 6))]

我需要在其中传递要从当前目录读取并显示在图像小部件中的绘图的文件名。

但这意味着我会将所有文件保存在一个文件夹中,而我宁愿将所有 PNG 保存在一个字典中,并在需要将给定文件名传递给 sg.Image() 时引用该字典。

我看到的优点是这样我不必占用硬盘驱动器上的空间来存储 PNG,也不必先写入然后从磁盘读取,我想直接从运行时在内存中的字典。

我无法实现这一点,因为代码似乎期望具有特定路径的文件名,而不是传递包含 PNG 的字典的特定值。

我怎样才能做到这一点?

4

2 回答 2

1

PySimpleGUI GitHub 上列出的演示程序之一是 Demo_Img_Viewer.py。在其中,您将找到一个函数,该函数接受文件名并返回您可以传递给元素update方法的数据。Image

此功能是该演示的一部分。它会将文件呈现为更新方法所期望的格式。

from PIL import Image

def get_img_data(f, maxsize=(1200, 850)):
    """
    Generate image data using PIL
    """
    img = Image.open(f)
    img.thumbnail(maxsize)
    bio = io.BytesIO()
    img.save(bio, format="PNG")
    del img
    return bio.getvalue()

您可以通过调用此函数并保存结果来遍历文件并“预渲染”它们。

然后稍后您可以使用这些预渲染图像之一更新您的图像元素。

window['My Image Element Key'].update(data=rendered)

于 2019-11-08T13:42:51.600 回答
1

问题:使用字典中的 PNG 文件在 PySimpleGUI (Python) 中的 Image 小部件中显示


class Image定义为:

class Image(Element):
    def __init__(self, filename=None, data=None, ...):
        """
        :param filename:  (str) image filename if there is a button image. 
                          GIFs and PNGs only.
        :param data:      Union[bytes, str] Raw or Base64 representation of the image
                          to put on button. 
        Choose either filename or data     

你可以做:

import PySimpleGUI as sg
import os

cwd = os.getcwd()
fname = 'image1.png'

with open('{}/{}'.format(cwd, fname)) as fh:
    image1 = fh.read()

[sg.Image(data=image1, key='key1', size=(5, 6))]

像这样的东西应该可以工作(假设有两个图像:)image1, image2


import PySimpleGUI as sg
# All the stuff inside your window.
layout [
         [sg.Image(data=image1, key='__IMAGE__', size=(5, 6))]
       ]

# Create the Window
window = sg.Window('Window Title', layout)

# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event in (None, 'Cancel'):   # if user closes window or clicks cancel
        break

    window.Element('_IMAGE_').Update(data=image2)

window.close()
于 2019-11-06T16:00:52.010 回答