簡體   English   中英

Tkinter中的configparser-使用ID制作新的ini文件?

[英]configparser in Tkinter - make new ini file with id?

我用tkinter和configparser制作了一個簡單的GUI應用程序,將值存儲在我的輸入/文本字段中。

但是我需要一些幫助。 我想讓用戶每次保存按鈕輸入時都給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()

如果要讓程序以升序保存所有配置文件,則可以執行以下操作:

# 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進行工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM