opt*_*opt 6 python user-interface pysimplegui
我有使用PySimpleGUI的Python GUI,它需要显示多个图形,我打算通过一组按钮进行导航。我知道我可以将所有图以PNG格式保存在给定的文件夹中,只需将它们加载到Image对象中,然后在单击按钮时使用元素的Update方法加载新图像。
如下所示的效果很好:
[sg.Image(filename=os.getcwd() + pngFileName, key='key1', size=(5, 6))]
Run Code Online (Sandbox Code Playgroud)
我需要传递要从当前目录中读取并显示在“图像”小部件中的图的文件名。
但这意味着我会将所有文件保存在一个文件夹中,而我更希望将所有PNG放在字典中,并在需要将给定文件名传递给sg.Image()时引用该字典。
我看到的好处是,这样一来,我不必占用硬盘驱动器上的空间来存储PNG,而且不必写然后从磁盘上读取,我想直接从磁盘上获取PNG会更快。运行时内存中的字典。
我无法实现此目标,因为代码似乎期望文件名具有特定路径,而不是传递包含PNG的字典的特定值。
我该如何实现?
问题:使用字典中的 PNG 文件在 PySimpleGUI (Python) 的图像小部件中显示
定义
class Image为:Run Code Online (Sandbox Code Playgroud)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))]
Run Code Online (Sandbox Code Playgroud)
像这样的东西应该可以工作(假设有两个图像:)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()
Run Code Online (Sandbox Code Playgroud)