You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现PySimpleGUI关闭后保留输入文件的历史路径?

如何在PySimpleGUI关闭后保留文件路径

核心思路是把用户选择的路径持久化存储到本地文件,下次启动程序时自动读取并填充到输入框里。下面是两种简单可行的实现方式:

方法一:用纯文本文件存储

这种方式代码简单,适合快速实现:

import PySimpleGUI as sg

# 用来存储路径的本地文件
PATH_STORE = "last_selected_path.txt"

def get_saved_path():
    """读取上次保存的路径,文件不存在则返回空"""
    try:
        with open(PATH_STORE, 'r', encoding='utf-8') as f:
            return f.read().strip()
    except FileNotFoundError:
        return ""

def save_current_path(path):
    """把当前路径写入本地文件"""
    try:
        with open(PATH_STORE, 'w', encoding='utf-8') as f:
            f.write(path)
    except Exception as e:
        print(f"保存路径失败: {e}")

# 界面布局,输入框默认值设为读取到的历史路径
layout = [
    [sg.Text("目标文件:"), sg.InputText(get_saved_path(), key="-FILE_PATH-"), sg.FileBrowse()],
    [sg.Button("确认"), sg.Button("退出")]
]

window = sg.Window("路径记忆示例", layout)

while True:
    event, values = window.read()
    # 关闭窗口或点击退出时,保存当前路径
    if event in (sg.WINDOW_CLOSED, "退出"):
        save_current_path(values["-FILE_PATH-"])
        break
    # 点击确认时也可以同步保存路径
    if event == "确认":
        current_path = values["-FILE_PATH-"]
        print(f"已选择路径: {current_path}")
        save_current_path(current_path)

window.close()

方法二:用INI配置文件存储

如果需要存储更多配置项,用INI文件更规范:

import PySimpleGUI as sg
import configparser

CONFIG_FILE = "app_config.ini"

def load_saved_path():
    config = configparser.ConfigParser()
    config.read(CONFIG_FILE, encoding='utf-8')
    # 不存在配置项时返回空字符串
    return config.get("UserSettings", "last_file_path", fallback="")

def save_path_to_config(path):
    config = configparser.ConfigParser()
    config["UserSettings"] = {"last_file_path": path}
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        config.write(f)

# 界面布局和交互逻辑和方法一一致
layout = [
    [sg.Text("目标文件:"), sg.InputText(load_saved_path(), key="-FILE_PATH-"), sg.FileBrowse()],
    [sg.Button("确认"), sg.Button("退出")]
]

window = sg.Window("路径记忆示例", layout)

while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, "退出"):
        save_path_to_config(values["-FILE_PATH-"])
        break
    if event == "确认":
        current_path = values["-FILE_PATH-"]
        print(f"已选择路径: {current_path}")
        save_path_to_config(current_path)

window.close()

关键说明

  • 程序启动时自动读取本地存储的路径,直接填充到输入框
  • 无论用户点击退出按钮还是直接关闭窗口,都会触发路径保存操作
  • 加入了异常捕获,避免文件读写失败导致程序崩溃

内容的提问来源于stack exchange,提问作者jess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:01:00