ProyectoFinalPython/app/ConfigMgr.py

83 lines
2.9 KiB
Python

import tkinter as tk
from tkinter import ttk
import os
import configparser
class ConfigMgr:
def __init__(self, top_level, config_changed_listener=None):
self.top_level = top_level
self.config_window = None
self.config = configparser.ConfigParser()
self.__load_config()
self.config_changed_listener=config_changed_listener
self.config.read('config.ini')
def __load_config(self):
if os.path.exists('config.ini'):
self.config.read('config.ini')
else:
print("Config file not found, creating default config file")
with open('config.ini', 'w') as f:
self.__write_default_config(f)
self.config.read('config.ini')
def __write_default_config(self, file):
chat_config = ("[Chat]\n"
"server=http://localhost:2020\n"
"name=User\n")
file.write(chat_config)
def display_config_window(self):
if (self.config_window is None
or not tk.Toplevel.winfo_exists(self.config_window)):
self.config_window = self.__build_config_window()
else:
self.config_window.lift()
def __build_config_window(self):
config_window = tk.Toplevel(self.top_level)
config_window.title("Config")
config_window.geometry("400x300")
notebook = ttk.Notebook(config_window)
notebook.pack(expand=True, fill="both")
chat_tab = ttk.Frame(notebook)
notebook.add(chat_tab, text="Chat Config")
chat_server_label = tk.Label(chat_tab, text="Chat Server URL")
chat_server_label.pack()
self.chat_server_variable = tk.StringVar()
try:
self.chat_server_variable.set(self.config["Chat"]["server"])
except KeyError:
self.chat_server_variable.set("")
chat_server_input = tk.Entry(chat_tab, textvariable=self.chat_server_variable)
chat_server_input.pack()
chat_name_label = tk.Label(chat_tab, text="Name in the Chat")
chat_name_label.pack()
self.chat_name_variable = tk.StringVar()
try:
self.chat_name_variable.set(self.config["Chat"]["name"])
except KeyError:
self.chat_name_variable.set("")
chat_name_input = tk.Entry(chat_tab, textvariable=self.chat_name_variable)
chat_name_input.pack()
self.save_button = tk.Button(config_window, text="Save", command=self.save_config)
self.save_button.pack(pady=10)
return config_window
def save_config(self):
self.config["Chat"] = {"server": self.chat_server_variable.get(),
"name": self.chat_name_variable.get()}
with open('config.ini', 'w') as configfile:
self.config.write(configfile)
self.config_changed_listener()
# Close window
self.config_window.destroy()