from os.path import exists import traceback from tkinter import messagebox import cage_func as func from User_Interface import HelmholtzGUI from User_Interface import ui_print import User_Interface as ui import globals as g import config_handling as config import csv_logging as log def program_end(): # called on exception or when user closes application g.exitFlag = True # tell everything else the application has been closed if g.app is not None: if g.app.pages[ui.ExecuteCSVMode].csv_thread is not None: # end possible csv execution thread g.app.pages[ui.ExecuteCSVMode].csv_thread.stop() # stop thread func.shut_down_all() # shut down devices if log.unsaved_data: # There is logged data that has not been saved yet # open pop-up to ask user if he wants to save the data: save_log = messagebox.askquestion("Save log data?", "There seems to be unsaved logging data. " "Do you wish to write it to a file now?") if save_log == 'yes': # user has chosen yes filepath = log.select_file() # let user select a file to write to log.write_to_file(log.log_data, filepath) # write the data to the chosen file if g.app is not None: g.app.destroy() # close application try: # start normal operations config.CONFIG_FILE = 'config.ini' # ToDo: remember what the last config file was if not exists(config.CONFIG_FILE): print("Config file not found, creating new from defaults.") config.reset_config_to_default() config.write_config_to_file(config.CONFIG_OBJECT) config.CONFIG_OBJECT = config.get_config_from_file(config.CONFIG_FILE) print("Starting setup...") func.setup_all() # initiate communication, set handles print("\nOpening User Interface...") g.app = HelmholtzGUI() g.exitFlag = False g.app.state('zoomed') # open maximized g.app.StatusDisplay.continuous_label_update(g.app, 500) # initiate regular Status Display updates (ms) ui_print("Program Initialized") config.check_config(config.CONFIG_OBJECT) # check config for values exceeding limits ui_print("\nStarting setup...") # do it again, so it is printed in the UI console ToDo: do it only once func.setup_all() # initiate communication, set handles g.app.protocol("WM_DELETE_WINDOW", program_end) # call program_end function if user closes the application g.app.mainloop() except Exception as e: # if there is an error, print what happened print("\nAn error occurred, Shutting down.") # shop pup-up error message: message = "%s.\nSee python console traceback for more details. " \ "\nShutting down devices, check equipment to confirm." % e messagebox.showerror("Error!", message) print(traceback.print_exc()) program_end() # safely close everything and shut down devices # ToDo: rework window closing code https://bytes.com/topic/python/answers/431323-detect-tkinter-window-being-closed # https://stackoverflow.com/questions/14694408/runtimeerror-main-thread-is-not-in-main-loop # ToDo: logging