如何在按下按钮时提交对文本文件的更改?

如何在按下按钮时提交对文本文件的更改?

我写了一篇小创建 GUI 的应用程序用于设置 uShare。目前它严重依赖“w”(写入)和“a”(附加)函数来生成/编辑 ushare.conf 文件。但我一直在尝试找到一种方法,让应用程序存储所有更改,直到按下保存按钮,然后才将它们提交到实际文件中。我认为这是让用户每次更改任何字段时都按 Enter 键的最佳方法(并且确实允许使用 GtkCheckButton)。

答案1

如果您想像这样存储配置,我建议您使用 PythonConfigParser模块。请注意,您应该确保将配置文件存储在中~/.config/<your-app-name>。您可以像这样存储配置:

import ConfigParser
import xdg.BaseDirectory

# set the configdir to ~/.config/ushare
configdir = os.path.join(xdg.BaseDirectory.xdg_config_home, "ushare")

# check if the dir exists and if not, create it
if not os.path.exists(configdir):
    os.makedirs(configdir)

# create configparser object
config = ConfigParser.RawConfigParser()
cfile = os.path.join(configdir, "ushare.conf")

# add your config items - see the ConfigParser docs for how to do this

# later in your app add this when the user presses the button to save the config:

with open(cfile, 'wb') as configfile:
    config.write(configfile)

请注意:我实际上并没有运行此代码,只是将其写在这里,但它应该可以正常工作。

相关内容