简体   繁体   中英

configparser in Tkinter - make new ini file with id?

i have made a simple GUI app, with tkinter and configparser, to store the values in my entry/text fields.

But i need help with something. I want to make the pogram assign a new ini file every time the user saves the input from the button and give the inifile a ID starting from 1 to infinite

So the user fill's all entry's and hits the save all information button. The gui must then generate a new inifile (1).

def saveConfig():
    filename = "config.ini"
    file = open(filename, 'w')
    Config = configparser.ConfigParser()
    Config.add_section('ORDERDATA')
    Config.set("ORDERDATA", "REKVIRENT", e1.get())
    Config.set("ORDERDATA", "MODTAGER", e2.get())
    Config.set("ORDERDATA", "PATIENTFORNAVN", e3.get())
    Config.set("ORDERDATA", "PATIENTEFTERNAVN", e4.get())
    Config.set("ORDERDATA", "CPR", e7.get())
    Config.set("ORDERDATA", "DOKUMENTATIONSDATO", e5.get())
    Config.set("ORDERDATA", "ØNSKET UNDERSØGELSE", e6.get())
    Config.set("ORDERDATA", "ANAMNESE", t1.get('1.0', END))
    Config.set("ORDERDATA", "INDIKATION", t2.get('1.0', END))
    Config.write(file)
    file.close()

If you want your program to save all your configuration files with ascending numbers, you could do the following:

# Python 2.7
import os
import ConfigParser as cp
import Tkinter as tk

def saveConfig():
    config = cp.ConfigParser()
    config.add_section("ORDERDATA")
    config.set("ORDERDATA", "REKVIRENT", e1.get())
    # Set all your settings here
    # Using os.listdir(), you can get the files in a folder in a list
    list_files = os.listdir(os.getcwd())
    # You can then convert the names of the files into integers for all
    # .ini files
    list_numbers = [int(x[:-4]) for x in list_files if x.endswith(".ini")]
    # If the length of this new list is 0, max will throw a ValueError
    if len(list_numbers) != 0:
        # Calculate the new file number by adding one to the highest found number
        new_file_num = max(list_numbers) + 1
    # To prevent the ValueError, set the number to 1 if no files are present
    else:
        new_file_num = 1
    # Derive the name of the file here
    new_file_name = str(new_file_num) + ".ini"
    # Open the file and write to it
    with open(new_file_name, "w") as file_obj:
        config.write(file_obj)


root = tk.Tk()
e1 = tk.Entry(root)
button = tk.Button(root, text="Click me!", command=saveConfig)
e1.pack()
button.pack()
root.mainloop()

For Python 3, you would only have to change the imports. Tested and working using Python 2.7 on Ubuntu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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