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

configparser in Tkinter - make new ini file with id?

我用 tkinter 和 configparser 制作了一个简单的 GUI 应用程序,用于将值存储在我的 entry/text 字段中。

但是我需要一些帮助。我想让程序在每次用户保存按钮输入时分配一个新的 ini 文件,并给 inifile 一个从 1 到无限

的 ID

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

如果你想让你的程序保存你所有的配置文件,你可以这样做:

# 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 进行测试和工作