gpt-4-0314· openai
Suzhen/CodeChat
Pysimplegui中用sg.image显示了一张照片,如何再次获得这张照片的路径
- User
Pysimplegui中用sg.image显示了一张照片,如何再次获得这张照片的路径
- Assistant
要在 PySimpleGUI 中获取已显示的图像的路径,您可以使用给 Image 元素设置的 key。首先,确保在创建 Image 元素时为其分配一个 key,如下所示:
import PySimpleGUI as sg image_file = "path/to/your/image.png" # 创建一个带有 Image 元素的布局 layout = [[sg.Image(filename=image_file, key="IMG_KEY")], # 添加其他需要的元素 ] # 创建窗口并执行主事件循环 window = sg.Window("Image Example", layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break window.close()接下来,要获取图像的路径,可以通过 Image 元素的 filename 属性轻松实现。例如,如果要在点击某个按钮时获取 image_file 的路径,可以这样做:
# 在布局添加一个按钮 layout = [[sg.Image(filename=image_file, key="IMG_KEY")], [sg.Button("Get Image Path")], # 添加其他需要的元素 ] # ... while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == "Get Image Path": img_path = window["IMG_KEY"].filename print(f"Image Path: {img_path}")这样,在点击按钮时,程序会打印出图像的路径。
- User
image_path is null
- Assistant
抱歉刚刚的回答中出现了误导。在获取图像路径时,需要在初始化该图像时将路径保存到全局变量中。下面展示了如何实现这个方法:
import PySimpleGUI as sg image_file = "path/to/your/image.png" # 创建一个带有 Image 元素的布局 layout = [[sg.Image(filename=image_file, key="IMG_KEY")], [sg.Button("Get Image Path")], # 添加其他需要的元素 ] # 创建窗口并执行主事件循环 window = sg.Window("Image Example", layout) # 创建一个字典用于保存图像路径 image_paths = {"IMG_KEY": image_file} while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == "Get Image Path": img_path = image_paths["IMG_KEY"] print(f"Image Path: {img_path}") window.close()在这个示例中,我们创建了一个名为 image_paths 的字典,将图像元素的 key (在本例中是
IMG_KEY)和对应的图像路径一起保存。 然后在 "Get Image Path" 按钮的事件处理器中,我们从字典中检索 key 对应的图像路径,并打印出来。这样做就可以获得图像路径。