简体   繁体   English

使用tkinter和configparser在按钮按下时提交多个配置文件更改

[英]Committing multiple config file changes on button press with tkinter and configparser

I have a program that, has a menu built with tkinter. 我有一个程序,有一个用tkinter构建的菜单。 There are several buttons on the menu and when pressed allows the user to pick certain locations for files. 菜单上有几个按钮,按下后允许用户选择文件的特定位置。 Here is that code: 这是该代码:

def open_vend_direct():
    vend_directory = filedialog.askopenfilename(
        initialdir="/", title="Select file", filetypes=(("Excel Files (CSV)", "*.csv"), ("all files", "*.*")))
    parser = ConfigParser()
    parser.read('config.ini')
    parser.set('VendorList','List_Location',vend_directory)

def open_attach_direct():
    vend_attach_direct = filedialog.askdirectory()
    parser = ConfigParser()
    parser.read('config.ini')
    parser.set('VendorFile','file_Location',vend_attach_direct)

def open_log_direct():
    log_locate = filedialog.askdirectory()
    parser = ConfigParser()
    parser.read('config.ini')
    parser.set('LogFolder','log_location',log_locate)

I have another button that is supposed to Apply all changes. 我还有另一个应该应用所有更改的按钮。 For this function I tried this but it doesn't work: 对于此功能,我尝试了此操作,但不起作用:

def apply_option():
    parser = ConfigParser()
    parser.read('config.ini')
    with open('config.ini', 'w') as f:
        parser.write(f)

In the three button functions I used to have this: 在三个按钮功能中,我曾经有过这样的功能:

with open('config.ini', 'w') as f:
        parser.write(f)

This worked but the problem is everytime the user changes that file location it would save and update the program automatically. 这行得通,但问题是,每当用户更改文件位置时,它将自动保存并更新程序。 I would only like the changes to be saved when the "Apply Changes" button is pressed. 我只希望在按下“应用更改”按钮时保存更改。

Edit: I also have other options on the menu (checkbuttons that I would like the apply changes to affect as well) 编辑:菜单上还有其他选项(我希望应用更改也影响到的复选框)

Is it because they are all in different functions? 是否因为它们都具有不同的功能?

Every time you initiate parser and read file you reset your parser to values in yours config.ini. 每次启动解析器并读取文件时,都会将解析器重置为config.ini中的值。 So put initiation of parser and parser read out of functions in global. 因此把解析器的初始化和解析器从全局函数中读出来。 Then it should work. 然后它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM