Tkinter中的configparser - 使用id创建新的ini文件?

时间:2017-02-02 12:28:22

标签: python tkinter ini configparser

我创建了一个简单的GUI应用程序,使用tkinter和configparser,将值存储在我的输入/文本字段中。

但我需要帮助。每次用户保存按钮输入时,我想让pogram分配一个新的ini文件,并为inifile提供一个从1开始到无限的ID

因此,用户填写所有条目并点击“保存所有信息”按钮。然后gui必须生成一个新的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()

1 个答案:

答案 0 :(得分:0)

如果您希望程序使用升序号保存所有配置文件,则可以执行以下操作:

# 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()

对于Python 3,您只需要更改导入。在Ubuntu上使用Python 2.7进行测试和工作。