import tkinter as tk #Wird für das GUI benötigt. 
import runpy # Wird benötigt, um Python-Skripte durch einen Befehl auszuführen.
import os #Wird benötigt, um Terminal-Befehle durch einen Befehl auszuführen.
from picamera import PiCamera #Wird benötigt, um das Live-Video anzeigen zu können.
from PIL import Image, ImageTk #Wird benötigt, um in der Einrichtung das Ergebnisbild (.jpg) anzeigen zu können.
import threading #Wird benötigt, um das GIF im Hintergrund abspielen zu lassen.
import tkinter.ttk as ttk #Wird benötigt, um .csv-Datei im GUI anzeigen zu können.
import csv #Wird benötigt, um .csv-Datei im GUI anzeigen zu können.
from tkinter import filedialog #Wird für das Pfadauswahlfenster benötigt.
from tkinter.font import nametofont #Wird benötigt um die Schriftgröße der Überschriften in ttk.Treeview() zu ändern.
from numpy import log as ln #Wird für die Skalierung der Fenster bei anderen Bildschirmauflösungen als 1920x1080 benötigt.
import RPi.GPIO as GPIO #Wird für die Steuerung der LED benötigt.
from tkinter import messagebox #Wird für die Fehlermeldungen benötigt.
import sys #Wird für das Beenden des Programms benötigt.
import webbrowser #Wird für das Öffnen des Links zur Homepage benötigt.




#--------Einstellungen----------------------------------------------------------------------------------------------------------------------------------------------------
Speicherpfad = "/home/pi/LambdaSpektrometer"
        # Der Speicherpfad, unter dem der Programmordner gespeichert ist.
        # Das Argument hinter dem letzten Schrägstrich ist der Name des Ordners.
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------




# Hauptfenster
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
r = screen_width / 1920
labelfont = "TkDefaultFont " + str(int(10*r))
Settings = Speicherpfad + "/Settings.txt"
with open(Settings, "r") as sf:
    LED_connected_str = sf.readlines()[1].lstrip("LED_connected = ").rstrip("\n")
if LED_connected_str == "True":
    LED_connected = True
else:
    LED_connected = False
print("LED_connected=", LED_connected)
with open(Settings, "r") as sf:
    LED = int(sf.readlines()[2].lstrip("LED_pin = ").rstrip("\n"))
print("LED=", LED)
with open(Settings, "r") as sf:
    GIF_str = sf.readlines()[3].lstrip("show_GIF = ").rstrip("\n")
if GIF_str == "True":
    GIF = True
else:
    GIF = False
print("GIF=", GIF)
with open(Settings, "r") as sf:
    showinfo = sf.readlines()[4].lstrip("show_info = ").rstrip("\n")
print("showinfo=", showinfo)
root.title("Lambda")
if showinfo == "True":
    width = 1040 * r 
    height = 985 * r - int(ln(r) * 140)
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))
else:
    width = 870 * r - int(ln(r) * 140)
    height = 722 * r - int(ln(r) * 140)
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))
# Banner
hbg="midnight blue" #Hintergrund
hfg="snow2" #Textfarbe
header = tk.Frame(root, bg=hbg)
icon_image = Image.open(Speicherpfad + "/Images/icon.png")
icon_image2 = icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS)
icon_image3 = ImageTk.PhotoImage(icon_image2, master=root)
icon_image.close()
icon_label = tk.Label(header, image=icon_image3, bg=hbg)
header_text = tk.Label(header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
# LED Einstellungen
if LED_connected == True:
    GPIO.setmode(GPIO.BOARD) #Lege die Nummerierung der Pins fest
    GPIO.setwarnings(False) #Desaktiviere die Fehlermeldungen
    GPIO.setup(LED, GPIO.OUT) #Aktiviere die Kontrolle über die LED
# Neustart
def restart():
    root.destroy()
    runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")




# Dark Mode
with open(Settings, "r") as sf:
    dark_mode = sf.readlines()[0].lstrip("Dark_Mode = ").rstrip("\n")
print("dark_mode=", dark_mode)
if dark_mode == "True":
    bgc = "gray25" #background
    fgc = "snow2" #foreground
    abc = "gray15" #activebackground
    afc = "snow2" #activeforeground
    blu = "deep sky blue" #Kommentarfarbe
    ebg = "gray17" #Textfeldhintergrund
    efg = "white" #Textfeldvordergrund
else:
    bgc = "snow3" #background
    fgc = "black" #foreground
    abc = "snow2" #activebackground
    afc = "black" #activeforeground
    blu = "blue" #Kommentarfarbe
    ebg = "white" #Textfeldhintergrund
    efg = "black" #Textfeldvordergrund
root.config(bg=bgc)




# "Einstellungen" Fenster
def open_settings(event="<F11>"):
    settings_window = tk.Tk()
    settings_window.config(bg=bgc)
    settingsw_width = 842 * r
    settingsw_height = 1010 * r - int(ln(r) * 140)
    settingsw_x = (screen_width/2) - (settingsw_width/2)
    settingsw_y = (screen_height/2) - (settingsw_height/2)
    settings_window.geometry("%dx%d+%d+%d" % (settingsw_width, settingsw_height, settingsw_x, settingsw_y))
    settings_window.title("Lambda  |  Einstellungen")
    settings_header = tk.Frame(settings_window, bg=hbg)
    settings_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    settings_icon_image2 = settings_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    settings_icon_image3 = ImageTk.PhotoImage(settings_icon_image2, master=settings_window)
    settings_icon_label = tk.Label(settings_header, image=settings_icon_image3, bg=hbg)
    settings_icon_label.image = settings_icon_image3
    settings_icon_image.close()
    settings_header_text = tk.Label(settings_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    settings_header.pack(fill="x")
    settings_icon_label.pack(side="left", padx=5*r)
    settings_header_text.pack(side="right", padx=5*r)
    root.withdraw()
    with open(Settings, "r") as sf:
        dark_mode = sf.readlines()[0].lstrip("Dark_Mode = ").rstrip("\n")
    print("dark_mode=", dark_mode)
    with open(Settings, "r") as sf:
        led_connected = sf.readlines()[1].lstrip("LED_connected = ").rstrip("\n")
    print("led_connected=", led_connected)
    with open(Settings, "r") as sf:
        led_pin = sf.readlines()[2].lstrip("LED_pin = ").rstrip("\n")
    print("led_pin=", led_pin)
    with open(Settings, "r") as sf:
        show_gif = sf.readlines()[3].lstrip("show_GIF = ").rstrip("\n")
    print("show_gif=", show_gif)
    with open(Settings, "r") as sf:
        led_brightness = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
    print("led_brightness=", led_brightness)
    with open(Settings, "r") as sf:
        csv_mode = sf.readlines()[10].lstrip("csv_mode = ").rstrip("\n")
    print("csv_mode=", csv_mode)
    # Widgets
    dark_mode_labelframe = tk.LabelFrame(settings_window, text="Dark Mode:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    dark_mode_info_string = " Der Dark Mode ändert das Farbschema der Benutzeroberfläche zu dunkleren Farbtönen.                                                               "
    dark_mode_info = tk.Label(dark_mode_labelframe, width=int(822*r), text=dark_mode_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    dark_mode_radiobutton_frame = tk.Frame(dark_mode_labelframe, bg=bgc)
    dark_mode_var = tk.StringVar(settings_window)
    if dark_mode == "False":
        dark_mode_var.set("False")
    else:
        dark_mode_var.set("True")
    def dark_mode_select_standard(event="<Control-d>"):
        dark_mode_var.set("False")
    settings_window.bind("<Control-d>", dark_mode_select_standard)
    def dark_mode_select_alternative(event="<Alt-d>"):
        dark_mode_var.set("True")
    settings_window.bind("<Alt-d>", dark_mode_select_alternative)
    dark_mode_radiobutton1 = tk.Radiobutton(dark_mode_radiobutton_frame, text="Aus [Strg + D]", variable=dark_mode_var, value="False", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    dark_mode_radiobutton2 = tk.Radiobutton(dark_mode_radiobutton_frame, text="Ein [Alt + D]", variable=dark_mode_var, value="True", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    show_gif_labelframe = tk.LabelFrame(settings_window, text="Ladebalken-GIF:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    show_gif_info_string = ("Falls es zu wiederholten Performance-Problemen kommt, kann hier das Abspielen des Ladebalken-GIFs deaktiviert          \n"
                            "werden. In diesem Fall wird allerdings während Messvorgängen nichts angezeigt. Deswegen wird davon wenn nicht "
                            "zwingend nötig abgeraten."
                            )
    show_gif_info = tk.Message(show_gif_labelframe, width=int(822*r), text=show_gif_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    show_gif_radiobutton_frame = tk.Frame(show_gif_labelframe, bg=bgc)
    show_gif_var = tk.StringVar(settings_window)
    if show_gif == "True":
        show_gif_var.set("True")
    else:
        show_gif_var.set("False")
    def show_gif_select_standard(event="<Control-g>"):
        show_gif_var.set("True")
    settings_window.bind("<Control-g>", show_gif_select_standard)
    def show_gif_select_alternative(event="<Alt-g>"):
        show_gif_var.set("False")
    settings_window.bind("<Alt-g>", show_gif_select_alternative)
    show_gif_radiobutton1 = tk.Radiobutton(show_gif_radiobutton_frame, text="Ein [Strg + G]", variable=show_gif_var, value="True", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    show_gif_radiobutton2 = tk.Radiobutton(show_gif_radiobutton_frame, text="Aus [Alt + G]", variable=show_gif_var, value="False", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    led_settings_labelframe = tk.LabelFrame(settings_window, text="LED-Einstellungen:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    led_settings_info_string = (" Wenn ein LED-Schaltkreis wie im Schaubild \"LED_Anleitung.jpg\" im Programmordner an den RaspberryPi angeschlossen     \n"
                                " ist, wählen Sie \"LED angeschlossen\" um die LED über Lambda steuern zu können. Andernfalls wählen Sie \"Keine LED \n"
                                " angeschlossen\" und verwenden Sie eine externe Lichtquelle. "
                                )
    led_settings_info = tk.Label(led_settings_labelframe, width=int(822*r), text=led_settings_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    led_settings_radiobutton_frame = tk.Frame(led_settings_labelframe, bg=bgc)
    led_settings_var = tk.StringVar(settings_window)
    if led_connected == "True":
        led_settings_var.set("True")
    else:
        led_settings_var.set("False")
    def led_settings_select_standard(event="<Control-l>"):
        led_settings_var.set("True")
    settings_window.bind("<Control-l>", led_settings_select_standard)
    def led_settings_select_alternative(event="<Alt-l>"):
        led_settings_var.set("False")
    settings_window.bind("<Alt-l>", led_settings_select_alternative)
    led_settings_radiobutton1 = tk.Radiobutton(led_settings_radiobutton_frame, text="LED angeschlossen [Strg + L]", variable=led_settings_var, value="True", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    led_settings_radiobutton2 = tk.Radiobutton(led_settings_radiobutton_frame, text="Keine LED angeschlossen [Alt + L]", variable=led_settings_var, value="False", bg=bgc, fg=fgc, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    led_settings_info_string2 = ("\n"
                                 " Wie in \"LED_Anleitung.jpg\" im Programmordner beschrieben, geht Lambda davon aus, dass die Anode des \n"
                                 " LED-Schaltkreises über den Pin mit der Nummer 7 an den RaspberryPi verbunden ist. Wenn Sie einen anderen Pin \n"
                                 " benutzen möchten, stellen Sie sicher, dass es sich um einen GPIO-Pin handelt und geben Sie unten die Nummer des \n"
                                 " Pins ein, den Sie in Zukunft verwenden möchten. Klicken Sie auf \"Änderungen speichern und zurück zum Hauptfenster\" \n"
                                 " oder drücken Sie [Strg + S], schließen Sie Lambda, fahren sie den RaspberryPi herunter und ändern Sie den \n"
                                 " LED-Kreislauf zu Ihren Wünschen."
                                 )
    led_settings_info2 = tk.Label(led_settings_labelframe, width=int(822*r), text=led_settings_info_string2, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    led_settings_var2 = tk.StringVar(settings_window)
    led_settings_var2.set(led_pin)
    if led_connected == "True":
        def led_spinbox_up(event="<Up>"):
            if int(led_settings_var2.get()) < 40:
                led_settings_var2.set(str(int(led_settings_var2.get()) + 1))
            else:
                led_settings_var2.set("1")
        def led_spinbox_down(event="<Down>"):
            if int(led_settings_var2.get()) > 1:
                led_settings_var2.set(str(int(led_settings_var2.get()) - 1))
            else:
                led_settings_var2.set("40")
        settings_window.bind("<Up>", led_spinbox_up)
        settings_window.bind("<Down>", led_spinbox_down)
    led_settings_spinbox = tk.Spinbox(led_settings_labelframe, from_=1, to=40, width=int(5*r), justify="center", font="TkDefaultFont " + str(int(12*r)), highlightbackground=bgc,
                                      activebackground=abc, buttonbackground=bgc, bg=ebg, fg=efg, insertbackground=efg, selectbackground="green", selectforeground="white",
                                      wrap="true", textvariable=led_settings_var2)
    if led_connected == "False":
        led_settings_info2.config(fg="Gray65")
        led_settings_spinbox.config(state="disabled")
    led_test_labelframe = tk.LabelFrame(settings_window, text="LED-Test:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    led_test_info_string = " Hier können Sie den LED-Kreislauf testen. Mit dem Slider können Sie die gewünschte Helligkeit in Prozent einstellen."
    led_test_info = tk.Label(led_test_labelframe, width=int(822*r), text=led_test_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    settings_led_scale = tk.Scale(led_test_labelframe, from_=0, to=100, bg=bgc, activebackground=abc, font=labelfont, fg=fgc,
                                  highlightbackground=bgc, troughcolor=ebg, orient="horizontal", length=int(700*r))
    settings_led_scale.set(float(led_brightness))
    def move_left(event="<Left>"):
        settings_led_scale.set(settings_led_scale.get() - 1)
    def move_right(event="<Down>"):
        settings_led_scale.set(settings_led_scale.get() + 1)
    settings_window.bind("<Left>", move_left)
    settings_window.bind("<Right>", move_right)
    def turn_led_on(event="<Control-t>"):
        os.system("pkill -9 -f led.py")
        GPIO.output(LED, GPIO.LOW)
        led_brightness_new = settings_led_scale.get()
        with open(Settings, "r") as sf:
            settings = sf.readlines()
        with open(Settings, "w") as sf:
            settings[6] = "LED_brightness = " + str(led_brightness_new) + "\n"
            sf.writelines(settings)
        print("led_brightness_new=", led_brightness_new)
        if led_brightness_new == 100:
            GPIO.output(LED, GPIO.HIGH)
        else:
            t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
            t_led.daemon = True
            t_led.start()
    def turn_led_off(event="<Alt-t>"):
        os.system("pkill -9 -f led.py")
        GPIO.output(LED, GPIO.LOW)
    settings_led_pane = tk.PanedWindow(led_test_labelframe, bg=bgc)
    settings_led_on = tk.Button(settings_led_pane, text="LED Einschalten [Strg + T]", command=turn_led_on, font=labelfont, fg=fgc, bg=bgc, activebackground=abc,
                                activeforeground=afc, highlightbackground=bgc)
    settings_window.bind("<Control-t>", turn_led_on)
    settings_led_pane.add(settings_led_on)
    settings_led_off = tk.Button(settings_led_pane, text="LED Ausschalten [Alt + T]", command=turn_led_off, font=labelfont, fg=fgc, bg=bgc, activebackground=abc,
                                 activeforeground=afc, highlightbackground=bgc)
    settings_window.bind("<Alt-t>", turn_led_off)
    settings_led_pane.add(settings_led_off)
    if led_connected == "False":
        led_test_labelframe.config(fg="Gray65")
        led_test_info.config(fg="Gray65")
        settings_led_scale.config(state="disabled", fg="Gray65")
        settings_led_on.config(state="disabled")
        settings_led_off.config(state="disabled")    
    csv_mode_labelframe = tk.LabelFrame(settings_window, text="csv-Stil:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    csv_mode_info_string = " Hier können Sie einstellen, in welchem Stil die csv-Dateien gespeichert und geöffnet werden sollen.                                              "
    csv_mode_info = tk.Label(csv_mode_labelframe, width=int(822*r), text=csv_mode_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    csv_mode_radiobutton_frame = tk.Frame(csv_mode_labelframe, bg=bgc)
    csv_mode_radiobutton_frame2 = tk.Frame(csv_mode_labelframe, bg=bgc)
    csv_mode_var = tk.StringVar(settings_window)
    if csv_mode == "German":
        csv_mode_var.set("German")
    else:
        csv_mode_var.set("English")
    def csv_mode_select_standard(event="<Control-y>"):
        csv_mode_var.set("German")
    settings_window.bind("<Control-y>", csv_mode_select_standard)
    def csv_mode_select_alternative(event="<Alt-y>"):
        csv_mode_var.set("English")
    settings_window.bind("<Alt-y>", csv_mode_select_alternative)
    csv_mode_radiobutton1 = tk.Radiobutton(csv_mode_radiobutton_frame, text="Deutsch [Strg + Y]: Komma als Dezimalzeichen, Semikolon als Trennzeichen", variable=csv_mode_var, 
                                           value="German", bg=bgc, fg=fgc, font=labelfont, highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    csv_mode_radiobutton2 = tk.Radiobutton(csv_mode_radiobutton_frame2, text="Englisch [Alt + Y]: Punkt als Dezimalzeichen, Komma als Trennzeichen", variable=csv_mode_var, 
                                           value="English", bg=bgc, fg=fgc, font=labelfont, highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    csv_mode_info_string2 = " ACHTUNG: Nach dem Ändern können mit dem anderen Stil erstellte csv-Dateien nicht mehr geöffnet werden!                                           "
    csv_mode_info2 = tk.Label(csv_mode_labelframe, width=int(822*r), text=csv_mode_info_string2, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")  
    reset_settings_labelframe = tk.LabelFrame(settings_window, text="Standardeinstellungeninstellungen wiederherstellen, Lambda zurücksetzen oder deinstallieren:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    reset_settings_info_string = " Hier können die Einstellungen auf dieser Seite oder das gesamte Programm zurückgesetzt bzw. deinstalliert werden."
    reset_settings_info = tk.Label(reset_settings_labelframe, width=int(822*r), text=reset_settings_info_string, bg=bgc, fg=fgc, font=labelfont, anchor="w", justify="left")
    def restore_settings(event="<F10>"):
        mb_message_string = ("Wollen Sie die Standardeinstellungen wiederherstellen? Ihre gespeicherten Daten für den Speicherpfad, die Verschlusszeit "
                             "der Kamera und die Daten aus der Einrichtung des Spektrometers bleiben erhalten."
                            )
        mb = messagebox.askyesno(title="Standardeinstellungen wiederherstellen?", message=mb_message_string)
        if mb == True:
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[0] = "Dark_Mode = False\n"
                settings[1] = "LED_connected = True\n"
                settings[2] = "LED_pin = 7\n"
                settings[3] = "show_GIF = True\n"
                settings[6] = "LED_brightness = 100\n"
                settings[10] = "csv_mode = German"
                sf.writelines(settings)
            print("settings restored")
            settings_window.destroy()
            root.destroy()
            runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")
    def reset_settings(event="<Control-F10>"):
        mb_message_string = ("Wollen Sie Lambda wirklich komplett zurücksetzen? Die Einrichtung muss dann vor der nächsten Verwendung erneut "
                             "durchgeführt werden, aber alle bereits gespeicherten Dateien bleiben erhalten."
                            )
        mb = messagebox.askyesno(title="Lambda zurücksetzen?", message=mb_message_string)
        if mb == True:
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[0] = "Dark_Mode = False\n"
                settings[1] = "LED_connected = True\n"
                settings[2] = "LED_pin = 7\n"
                settings[3] = "show_GIF = True\n"
                settings[4] = "show_info = True\n"
                settings[5] = "save_path = /home/pi/Desktop/Mein_erstes_Spektrum\n"
                settings[6] = "LED_brightness = 100\n"
                settings[7] = "shutter_time = 40000\n"
                settings[8] = "spectrum_angle = 0\n"
                settings[9] = "spectrum_scale = 0.6\n"
                settings[10] = "csv_mode = German"
                sf.writelines(settings)
            print("default settings restored")
            settings_window.destroy()
            root.destroy()
            runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")
    def uninstall(event="<Alt-F10>"):
        mb_message_string = ("Wollen Sie Lambda wirklich deinstallieren? Dabei gehen sämtliche Einstellungen verloren! "
                             "Alle bereits gespeicherten Dateien bleiben erhalten."
                            )
        mb = messagebox.askyesno(title="Lambda deinstallieren?", message=mb_message_string)
        if mb == True:
            byebye_window = tk.Tk()
            byebye_window.config(bg=bgc)
            byebyew_width = 500 * r
            byebyew_height = 80 * r - int(ln(r) * 140)
            byebyew_x = (screen_width/2) - (byebyew_width/2)
            byebyew_y = (screen_height/2) - (byebyew_height/2)
            byebye_window.geometry("%dx%d+%d+%d" % (byebyew_width, byebyew_height, byebyew_x, byebyew_y))
            byebye_window.title("Auf Wiedersehen!")
            byebye_header = tk.Frame(byebye_window, bg=hbg)
            byebye_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
            byebye_icon_image2 = byebye_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            byebye_icon_image3 = ImageTk.PhotoImage(byebye_icon_image2, master=byebye_window)
            byebye_icon_label = tk.Label(byebye_header, image=byebye_icon_image3, bg=hbg)
            byebye_icon_label.image = byebye_icon_image3
            byebye_icon_image.close()
            byebye_header.pack(fill="x")
            byebye_icon_label.pack(side="left", padx=5*r)
            settings_window.withdraw()
            root.withdraw()
            bye = tk.Message(byebye_window, width=450*r, justify="left", text="Vielen Dank, dass Sie Lambda verwendet haben!", bg=bgc, fg=blu, font=labelfont + " bold")
            bye2 = tk.Message(byebye_window, width=450*r, justify="left", text="Lambda ist nun deinstalliert. Sie können dieses Fenster schließen.", bg=bgc, fg=fgc, font=labelfont)
            bye.pack()
            bye2.pack()
            def delete():
                import shutil
                shutil.rmtree(Speicherpfad)
                os.remove(r"/home/pi/Desktop/Lambda")
                sys.exit()
            t_bye = threading.Thread(target=delete, name="Deinstalliere Lambda...") 
            t_bye.daemon = True
            t_bye.start()
            byebye_window.mainloop()
    settings_window.bind("<F10>", restore_settings)
    settings_window.bind("<Control-F10>", reset_settings)
    settings_window.bind("<Alt-F10>", uninstall)
    reset_settings_pane = tk.PanedWindow(reset_settings_labelframe, bg=bgc)
    reset_settings_restore = tk.Button(reset_settings_pane, text="Einstellungen zurücksetzen [F10]", command=restore_settings, font=labelfont, fg=fgc, bg=bgc, activebackground=abc,
                                activeforeground=afc, highlightbackground=bgc)
    reset_settings_pane.add(reset_settings_restore)
    reset_settings_reset = tk.Button(reset_settings_pane, text="Lambda zurücksetzen [Strg + F10]", command=reset_settings, font=labelfont, fg=fgc, bg=bgc, activebackground=abc,
                                activeforeground=afc, highlightbackground=bgc)
    reset_settings_pane.add(reset_settings_reset)
    reset_settings_uninstall = tk.Button(reset_settings_pane, text="Lambda deinstallieren [Alt + F10]", command=uninstall, font=labelfont, fg=fgc, bg=bgc, activebackground=abc,
                                activeforeground=afc, highlightbackground=bgc)
    reset_settings_pane.add(reset_settings_uninstall)
    # Zurück- und Schließen-Buttons
    def abort_settings(event="<Escape>"):
        with open(Settings, "r") as sf:
            settings = sf.readlines()
        with open(Settings, "w") as sf:
            settings[6] = "LED_brightness = " + led_brightness + "\n"
            sf.writelines(settings)
        print("led_brightness=", led_brightness)
        if led_connected == "True":
            turn_led_off()
        settings_window.destroy()
        root.deiconify()
    def close_settings(event="<Control-s>"):
        dark_mode_new = dark_mode_var.get()
        show_gif_new = show_gif_var.get()
        led_connected_new = led_settings_var.get()
        led_pin_new = led_settings_var2.get()
        led_brightness_new = settings_led_scale.get()
        csv_mode_new = csv_mode_var.get()
        with open(Settings, "r") as sf:
            settings = sf.readlines()
        with open(Settings, "w") as sf:
            settings[0] = "Dark_Mode = " + dark_mode_new + "\n"
            settings[1] = "LED_connected = " + led_connected_new + "\n"
            settings[2] = "LED_pin = " + led_pin_new + "\n"
            settings[3] = "show_GIF = " + show_gif_new + "\n"
            settings[6] = "LED_brightness = " + str(led_brightness_new) + "\n"
            settings[10] = "csv_mode = " + csv_mode_new + "\n"
            sf.writelines(settings)
        print("dark_mode_new=", dark_mode_new)
        print("led_connected_new=", led_connected_new)
        print("led_pin_new=", led_pin_new)
        print("show_gif_new=", show_gif_new)
        print("led_brightness_new=", led_brightness_new)
        if led_connected == "True":
            turn_led_off()
        settings_window.destroy()
        root.destroy()
        runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")
    settings_decision_pane = tk.PanedWindow(settings_window, bg=bgc)
    settings_back = tk.Button(settings_decision_pane, text="Zurück und Änderungen verwerfen [Esc]", command=abort_settings, font=labelfont, fg="white", bg="red", activebackground="red3", activeforeground="white", highlightbackground=bgc)
    settings_window.bind("<Escape>", abort_settings)
    settings_decision_pane.add(settings_back)
    settings_success = tk.Button(settings_decision_pane, text="Änderungen speichern und zurück zum Hauptfenster [Strg + S]", command=close_settings, font=labelfont, fg="white", bg="green", activebackground="dark green", activeforeground="white", highlightbackground=bgc)
    settings_window.bind("<Control-s>", close_settings)
    settings_decision_pane.add(settings_success)
    # Räumliche Anordnung der Widgets
    dark_mode_labelframe.pack(padx=10*r, pady=10*r)
    dark_mode_info.pack()
    dark_mode_radiobutton_frame.pack()
    show_gif_labelframe.pack(padx=10*r, pady=10*r)
    show_gif_info.pack()
    show_gif_radiobutton_frame.pack()
    led_settings_labelframe.pack(padx=10*r, pady=10*r)
    led_settings_info.pack()
    led_settings_radiobutton_frame.pack()
    led_settings_info2.pack()
    led_settings_spinbox.pack(pady=5*r)
    led_test_labelframe.pack(padx=10*r, pady=10*r)
    led_test_info.pack()
    settings_led_scale.pack()
    settings_led_pane.pack(pady=10*r)
    csv_mode_labelframe.pack(padx=10*r, pady=10*r)
    csv_mode_info.pack()
    csv_mode_radiobutton_frame.pack(fill="x")
    csv_mode_radiobutton_frame2.pack(fill="x")
    csv_mode_info2.pack()
    reset_settings_labelframe.pack(padx=10*r, pady=10*r)
    reset_settings_info.pack()
    reset_settings_pane.pack()
    settings_decision_pane.pack(side="bottom", pady=10*r)
    # Fenster bleibt bis zur manuellen Schließung geöffnet!
    settings_window.mainloop()

    
    


# "Über Lambda" Fenster
def about(event="<F12>"):
    about_window = tk.Tk()
    about_window.config(bg=bgc)
    aboutw_width = 460 * r
    aboutw_height = 820 * r - int(ln(r) * 140)
    aboutw_x = (screen_width/2) - (aboutw_width/2)
    aboutw_y = (screen_height/2) - (aboutw_height/2)
    about_window.geometry("%dx%d+%d+%d" % (aboutw_width, aboutw_height, aboutw_x, aboutw_y))
    about_window.title("Über Lambda")
    root.withdraw()
    def open_homepage(event="<Control-w>"):
        webbrowser.open("https://www.chemie.uni-wuerzburg.de/didaktik/lehrende/low-cost-messgeraete/vis-spektrometer/")
    def about_close(event="<Escape>"):
        about_window.destroy()
        root.deiconify()
    #Widgets
    icon_image = Image.open(Speicherpfad + "/Images/icon.png") 
    icon_image2 = icon_image.resize((int(400*r), int(400*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    icon_image3 = ImageTk.PhotoImage(icon_image2, master=about_window)
    icon_label = tk.Label(about_window, image=icon_image3, bg=bgc)
    program_name = tk.Label(about_window, text="Lambda 1.1", font="TkDefaultFont " + str(int(30*r)) + " bold", bg=bgc, fg=fgc)
    cc_image = Image.open(Speicherpfad + "/Images/CC.png") 
    cc_image2 = ImageTk.PhotoImage(cc_image, master=about_window)
    cc_label = tk.Label(about_window, image=cc_image2, bg=bgc)
    about_string = ("Dieses Werk ist lizenziert unter einer Creative Commons Namensnennung 4.0 International Lizenz.\n"
                    "Beruht auf dem Werk von Tony Butterfield unter https://github.com/tonbut/RPiSpectrometer.\n"
                    "\n"
                    "Lambda wurde von Maurice Kahre im Rahmen einer Zulassungsarbeit an der Didaktik der Chemie (Fakultät für Chemie und Pharmazie) "
                    "der Julius-Maximilians-Universität Würzburg unter der Betreuung von Patrick Gräb erstellt. Die Software wurde entwickelt um einfach, schnell und gut präsentierbar "
                    "mit einem RaspberryPi und einem (Low-Cost) Spektrometer Extinktionsspektren aufnehmen zu können."
                   )
    about_message = tk.Message(about_window, width=450*r, justify="left", text=about_string, bg=bgc, fg=fgc, font=labelfont)
    about_link_button = tk.Button(about_window, text="Zur Homepage [Strg + W]", bg=bgc, fg=blu, command=open_homepage, cursor="hand2",
                                   font=labelfont, activebackground=abc, activeforeground=afc, highlightbackground=bgc)
    about_window.bind("<Control-w>", open_homepage)
    about_close_button = tk.Button(about_window, text="Schließen und zurück zum Hauptfenster [Esc]", bg="red", fg="white", command=about_close,
                                   font=labelfont, activebackground="red3", activeforeground="white", highlightbackground=bgc)
    about_window.bind("<Escape>", about_close)
    #Anordnung der Widgets
    icon_label.pack()
    program_name.pack(pady=5*r)
    cc_label.pack()
    about_message.pack(pady=5*r)
    about_link_button.pack()
    about_close_button.pack(side="bottom", pady=10*r)    
    about_window.mainloop()




# Hilfefenster
def help_me(event="<F1>"):
    help_window = tk.Tk()
    help_window.config(bg=bgc)
    helpw_width = 950 * r
    helpw_height = 540 * r - int(ln(r) * 140)
    helpw_x = (screen_width/2) - (helpw_width/2)
    helpw_y = (screen_height/2) - (helpw_height/2)
    help_window.geometry("%dx%d+%d+%d" % (helpw_width, helpw_height, helpw_x, helpw_y))
    help_window.title("Lambda  |  Hilfe")
    helpw_header = tk.Frame(help_window, bg=hbg)
    helpw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    helpw_icon_image2 = helpw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    helpw_icon_image3 = ImageTk.PhotoImage(helpw_icon_image2, master=help_window)
    helpw_icon_label = tk.Label(helpw_header, image=helpw_icon_image3, bg=hbg)
    helpw_icon_label.image = helpw_icon_image3 
    helpw_icon_image.close()
    helpw_header_text = tk.Label(helpw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    helpw_header.pack(fill="x")
    helpw_icon_label.pack(side="left", padx=5*r)
    helpw_header_text.pack(side="right", padx=5*r)
    root.withdraw()
    def kill_all_gifs(event="<Control-g>"):
        os.system("pkill -9 -f gif_main.py")
    help_window.bind("<Control-g>", kill_all_gifs)
    help_string = ("\N{Bullet} \"Der Ladebalken verschwindet nicht.\" \n"
                   "         Drücken Sie während dieses Fenster geöffnet ist [Strg + G] oder führen Sie im Terminal (Taskleiste) folgenden Befehl aus:\n"
                   "         pkill -9 -f gif_main.py \n"
                   "\n"
                   "\N{Bullet} \"Der RaspberryPi friert bei der Ausführung des Programms ein.\" \n"
                   "         Es ist möglich, dass die Anzeige des Ladebalken-GIFs die CPU überlastet. Um die Anzeige zu deaktivieren, öffnen Sie im\n"
                   "         Hauptfenster die Einstellungen und schalten Sie das Ladebalken-GIF aus. Wenn ein LED-Kreislauf an den RaspberryPi angeschlossen\n"
                   "         ist und die Helligkeit der LED nicht auf 100 % eingestellt ist kann dies ebenfalls zu Leistungseinbußen führen, da die Dimmung\n"
                   "         durch sehr schnelles An- und Abschalten der LED Rechenleistung belegt. In diesem Fall stellen Sie die Helligkeit im \n"
                   "         Einstellungsfenster auf 100 % und belassen Sie es stets dabei.\n"
                   "\n"
                   "\N{Bullet} \"Ich möchte den Programmordner verschieben.\"\n"
                   "         Davon wird zwar abgeraten, aber es ist möglich. Öffnen Sie dazu die \"Einrichtung\"-Datei im Programmordner und folgen Sie den \n"
                   "         Anweisungen unter \"Pfad des Programmordners ändern\".\n"
                   "\n"
                   "\N{Bullet} \"Ich möchte mir einen Beispielaufbau eines Low-Cost Spektrometers ansehen.\"\n"
                   "         Auf der Webseite der Didaktik der Chemie der Universität Würzburg (siehe Button \"Zur Homepage\" unten) finden Sie Bilder\n"
                   "         eines beispielhaften Aufbaus eines 3D-gedruckten Low-Cost Spektrometers wie es bei der Entwicklung dieses Programmes zum\n"
                   "         Einsatz kam. Dort finden Sie auch eine Datei, mit der Sie sich selber ein solches drucken können und eine Anleitung zum Aufbau!\n"  
                   )
    help_message = tk.Message(help_window, width=936*r, justify="left", text=help_string, bg=bgc, fg=fgc, font=labelfont)
    help_message.pack(padx=5*r, pady=5*r)
    def open_homepage(event="<Control-w>"):
        webbrowser.open("https://www.chemie.uni-wuerzburg.de/didaktik/lehrende/low-cost-messgeraete/vis-spektrometer/")
    help_link_button = tk.Button(help_window, text="Zur Homepage [Strg + W]", bg=bgc, fg=blu, command=open_homepage, cursor="hand2",
                                   font=labelfont, activebackground=abc, activeforeground=afc, highlightbackground=bgc)
    help_window.bind("<Control-w>", open_homepage)
    def help_close(event="<Escape>"):
        help_window.destroy()
        root.deiconify()
    help_close_button = tk.Button(help_window, text="Schließen und zurück zum Hauptfenster [Esc]", bg="red", fg="white", command=help_close, font=labelfont, activebackground="red3", activeforeground="white", highlightbackground=bgc)
    help_window.bind("<Escape>", help_close)
    help_close_button.pack(side="bottom", pady=10*r)
    mail_string = "Feedback oder andere Fragen: Schreiben Sie eine Mail an lambdaspectrometer@gmail.com"
    mail_label = tk.Message(help_window, width=1000*r, anchor="sw", font="TkDefaultFont " + str(int(13*r)) + " bold", text=mail_string, pady=10, bg=bgc, fg=fgc)
    mail_label.pack(side="bottom")
    help_link_button.pack(side="bottom")
    help_window.mainloop()




# GIF öffnen
def open_gif_main():
    os.system("python3 " + Speicherpfad + "/Python_scripts/gif_main.py")
    
    
    
    
# LED gedimmt anschalten
def led_on():
    print("led.py läuft")
    os.system("python3 " + Speicherpfad + "/Python_scripts/led.py")
    




# Einrichtung (Pop-up-Fenster)
def setup(event="<Control-e>"):
    setup_window = tk.Tk()
    setup_window.config(bg=bgc)
    sw_width = 544 * r
    sw_height = 564 * r - int(ln(r) * 140)
    sw_x = (screen_width/2) - (sw_width/2)
    sw_y = (screen_height/2) - (sw_height/2)
    setup_window.geometry("%dx%d+%d+%d" % (sw_width, sw_height, sw_x, sw_y))
    setup_window.title("Lambda  |  Einrichtung des Spektrometers")
    sw_header = tk.Frame(setup_window, bg=hbg)
    sw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    sw_icon_image2 = sw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    sw_icon_image3 = ImageTk.PhotoImage(sw_icon_image2, master=setup_window)
    sw_icon_label = tk.Label(sw_header, image=sw_icon_image3, bg=hbg)
    sw_icon_label.image = sw_icon_image3
    sw_icon_image.close()
    sw_header_text = tk.Label(sw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    sw_header.pack(fill="x")
    sw_icon_label.pack(side="left", padx=5*r)
    sw_header_text.pack(side="right", padx=5*r)
    root.withdraw() #Versteckt Hauptfenster ohne es zu zerstören. 

    # Kalibrierung: Verschlusszeit (Pop-up-Fenster)
    def setup_shutter_time_calibration(event="1"):
        stc_window = tk.Toplevel()
        stc_window.config(bg=bgc)
        stcw_width = 800 * r
        stcw_height = 860 * r - int(ln(r) * 140)
        stcw_x = (screen_width/2) - (stcw_width/2)
        stcw_y = (screen_height/2) - (stcw_height/2)
        stc_window.geometry("%dx%d+%d+%d" % (stcw_width, stcw_height, stcw_x, stcw_y))
        stc_window.title("Lambda  |  Kalibrierung: Verschlusszeit der Kamera und Helligkeit der LED")
        stc_header = tk.Frame(stc_window, bg=hbg)
        stc_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        stc_icon_image2 = stc_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        stc_icon_image3 = ImageTk.PhotoImage(stc_icon_image2, master=stc_window)
        stc_icon_label = tk.Label(stc_header, image=stc_icon_image3, bg=hbg)
        stc_icon_label.image = stc_icon_image3
        stc_icon_image.close()
        stc_header_text = tk.Label(stc_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        stc_header.pack(fill="x")
        stc_icon_label.pack(side="left", padx=5*r)
        stc_header_text.pack(side="right", padx=5*r)
        setup_window.withdraw()
        with open(Settings, "r") as sf:
            led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
        print("led=", led)
        with open(Settings, "r") as sf:
            st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
        print("st=", st)
        def take_new_picture():
            stc_window.withdraw()
            st_new = stc_st_scale.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[7] = "shutter_time = " + str(st_new) + "\n"
                sf.writelines(settings)
            print("st_new=", st_new)
            if LED_connected == True:
                led_new = stc_led_scale.get()
                with open(Settings, "r") as sf:
                    settings = sf.readlines()
                with open(Settings, "w") as sf:
                    settings[6] = "LED_brightness = " + str(led_new) + "\n"
                    sf.writelines(settings)
                print("led_new=", led_new)
                if led_new == 100:
                    GPIO.output(LED, GPIO.HIGH)
                else:
                    t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
                    t_led.daemon = True
                    t_led.start()            
            setup_file_path = Speicherpfad + "/Setup_files/setup "
            tc = str("python3 " + Speicherpfad + "/Python_scripts/calibration.py ")
            terminal_command = tc + setup_file_path + str(int(stc_st_scale.get())) 
            os.system(terminal_command)
            if LED_connected == True:
                if led_new is not 100:
                    os.system("pkill -9 -f led.py")
                GPIO.output(LED, GPIO.LOW)
            stc_window.deiconify()
        def refresh_image(event="n"):
            if GIF == True:
                t = threading.Thread(target=open_gif_main, name="Zeige GIF an") 
                t.daemon = True
                t.start()
            take_new_picture()
            os.system("pkill -9 -f gif_main.py")
            os.system("pkill -9 -f calibration.py")
            stc_lbl_image_new = Image.open(Speicherpfad + "/Setup_files/setup_Bild.jpg")
            stc_lbl_image2_new = stc_lbl_image_new.resize((int(648*r), int(486*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            stc_lbl_image3_new = ImageTk.PhotoImage(stc_lbl_image2_new, master=stc_window)
            stc_lbl.config(image=stc_lbl_image3_new)
            stc_lbl.image = stc_lbl_image3_new
            stc_lbl_image_new.close() 
        def stc_examples(event="b"): 
            stc_examples_window = tk.Tk()
            stc_examples_window.config(bg=bgc)
            stc_examples_w_width = 1454 * r
            stc_examples_w_height = 440 * r - int(ln(r) * 140)
            stc_examples_w_x = (screen_width/2) - (stc_examples_w_width/2)
            stc_examples_w_y = (screen_height/2) - (stc_examples_w_height/2)
            stc_examples_window.geometry("%dx%d+%d+%d" % (stc_examples_w_width, stc_examples_w_height, stc_examples_w_x, stc_examples_w_y))
            stc_examples_window.title("Lambda  |  Kalibrierung: Verschlusszeit der Kamera und Helligkeit der LED (Beispielbilder)")
            stc_examples_header = tk.Frame(stc_examples_window, bg=hbg)
            stc_examples_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
            stc_examples_icon_image2 = stc_examples_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            stc_examples_icon_image3 = ImageTk.PhotoImage(stc_examples_icon_image2, master=stc_examples_window)
            stc_examples_icon_label = tk.Label(stc_examples_header, image=stc_examples_icon_image3, bg=hbg)
            stc_examples_icon_label.image = stc_examples_icon_image3
            stc_examples_icon_image.close()
            stc_examples_header_text = tk.Label(stc_examples_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
            stc_examples_header.pack(fill="x")
            stc_examples_icon_label.pack(side="left", padx=5*r)
            stc_examples_header_text.pack(side="right", padx=5*r)
            def stc_examples_close(event="<Escape>"):
                stc_examples_window.destroy()
            #Widgets
            example_image = Image.open(Speicherpfad + "/Images/stc_example.png")
            example_image2 = example_image.resize((int(1450*r), int(338*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            example_image3 = ImageTk.PhotoImage(example_image2, master=stc_examples_window)
            example_label = tk.Label(stc_examples_window, image=example_image3, bg=bgc)    
            stc_examples_close_button = tk.Button(stc_examples_window, text="Fenster schließen [Esc]", bg="red", fg="white", command=stc_examples_close, font=labelfont, activebackground="red3", activeforeground="white", highlightbackground=bgc)
            stc_examples_window.bind("<Escape>", stc_examples_close)
            #Anordnung der Widgets
            example_label.pack(pady=5*r)
            stc_examples_close_button.pack(side="bottom", pady=10*r)    
            stc_examples_window.mainloop()
        def abort_stc(event="<Escape>"):
            stc_window.destroy()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[6] = "LED_brightness = " + str(led) + "\n"
                settings[7] = "shutter_time = " + str(st) + "\n"
                sf.writelines(settings)
            print("led=", led)
            print("st=", st)
            setup_window.deiconify()
            os.system("pkill -9 -f led.py")
        def close_stc(event="s"):
            led_new = stc_led_scale.get()
            st_new = stc_st_scale.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[6] = "LED_brightness = " + str(led_new) + "\n"
                settings[7] = "shutter_time = " + str(st_new) + "\n"
                sf.writelines(settings)
            print("led_new=", led_new)
            print("st_new=", st_new)
            stc_window.destroy()
            setup_window.deiconify()
            os.system("pkill -9 -f led.py")
            setup_welcome.config(fg="Gray65", font=labelfont)
            setup_shutter_time_calibration_labelframe.config(fg="Gray65", font=labelfont)
            spectrum_angle_calibration_labelframe.config(fg=fgc, font=labelfont + " bold")
            setup_shutter_time_calibration_button.config(text="Verschlusszeit kalibrieren \N{HEAVY CHECK MARK}", highlightbackground="green", state="disabled", font=labelfont)
            spectrum_angle_calibration_button.config(state="normal")
            setup_stc_info.config(fg="Gray65")
            setup_sac_info.config(fg=fgc)
                
        # Hinweise
        stc_info_labelframe = tk.LabelFrame(stc_window, text="Hinweise:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
        stc_info_string = ("Damit das Programm optimal arbeiten kann, darf die Helligkeit des aufgenommenen Bildes nicht zu hoch sein. "
                               "Passen Sie dafür rechts die Helligkeit der LED (in Prozent) und/oder unten die Verschlusszeit der Kamera "
                               "(in Mikrosekunden) an (Ersteres kann ignoriert werden, "
                               "falls für den Aufbau des Spektrometers keine LED an den RaspberryPi angeschlossen wurde, sondern eine externe "
                               "Lichtquelle verwendet wird. Es wird empfohlen, nur die Verschlusszeit zu ändern und die LED auf 100 % "
                               "Intensität zu lassen, da durch das Dimmen Ressourcen des RaspberryPi belegt werden. "
                               "Für eine Anleitung eines Beilspielaufbaus eines Low-Cost Spektrometers klicken Sie "
                               "im Hauptfenster auf \"Hilfe\"). \n"
                               "Unter \"Beispiele\" sind Beispielbilder abgebildet, die Ihnen zeigen, welche Helligkeit optimal ist. "
                               "Das folgende Bild wird durch Klicken auf \"Neues Bild aufnehmen\" oder Drücken von [N] aktualisiert!"
                              )
        stc_info_label = tk.Message(stc_info_labelframe, bg=bgc, fg=fgc, justify="left", width=int(750*r), font=labelfont, text=stc_info_string)
        stc_info_button = tk.Button(stc_info_labelframe, text="Beispiele [B]", bg=bgc, fg=fgc, command=stc_examples, font=labelfont, activebackground=abc, activeforeground=fgc, highlightbackground=bgc)
        stc_window.bind("b", stc_examples)
        # Bild
        stc_lbl_pane = tk.PanedWindow(stc_window, bg=bgc)
        stc_lbl_image = Image.open(Speicherpfad + "/Setup_files/setup_Bild.jpg")
        stc_lbl_image2 = stc_lbl_image.resize((int(648*r), int(486*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        stc_lbl_image3 = ImageTk.PhotoImage(stc_lbl_image2, master=stc_window)
        stc_lbl = tk.Label(stc_window, image=stc_lbl_image3)
        stc_lbl_image.close()
        stc_lbl_pane.add(stc_lbl)
        # Helligkeits-Slider
        stc_led_scale = tk.Scale(stc_window, from_=100, to=0, bg=bgc, activebackground=abc, font=labelfont, fg=fgc,
                                 highlightbackground=bgc, troughcolor=ebg)
        stc_led_scale.set(float(led))
        stc_lbl_pane.add(stc_led_scale)
        def move_up(event="<Up>"):
            led_new = stc_led_scale.get()
            stc_led_scale.set(led_new + 1)
        def move_down(event="<Down>"):
            led_new = stc_led_scale.get()
            stc_led_scale.set(led_new - 1)
        stc_window.bind("<Up>", move_up)
        stc_window.bind("<Down>", move_down)
        # Verschlusszeit-Slider
        stc_st_scale = tk.Scale(stc_window, from_=1000, to=200000, orient="horizontal", length=int(700*r), 
                                bg=bgc, activebackground=abc, font=labelfont, fg=fgc, highlightbackground=bgc, troughcolor=ebg)
        stc_st_scale.set(st)
        def move_left(event="<Left>"):
            st_new = stc_st_scale.get()
            stc_st_scale.set(round(st_new, -3) - 1000)
        def move_right (event="<Right>"):
            st_new = stc_st_scale.get()
            stc_st_scale.set(round(st_new, -3) + 1000)
        stc_window.bind("<Left>", move_left)
        stc_window.bind("<Right>", move_right)
        # Zurück- und Schließen-Buttons
        stc_decision_pane = tk.PanedWindow(stc_window, bg=bgc)
        stc_back = tk.Button(stc_decision_pane, text="Zurück und Änderungen verwerfen [Esc]", command=abort_stc, font=labelfont, fg="white", bg="red", activebackground="red3", activeforeground="white", highlightbackground=bgc)
        stc_window.bind("<Escape>", abort_stc)
        stc_decision_pane.add(stc_back)
        stc_renew = tk.Button(stc_decision_pane, text="Neues Bild aufnehmen [N]", command=refresh_image, font=labelfont, bg="orange", activebackground="dark orange", activeforeground="black", highlightbackground=bgc)
        stc_window.bind("n", refresh_image)
        stc_decision_pane.add(stc_renew)
        stc_success = tk.Button(stc_decision_pane, text="Speichern und weiter [S]", command=close_stc, font=labelfont, fg="white", bg="green", activebackground="dark green", activeforeground="white", highlightbackground=bgc)
        stc_window.bind("s", close_stc)
        stc_decision_pane.add(stc_success)
        
        #Räumliche Anordnung der Widgets
        stc_info_labelframe.pack(padx=10*r, pady=10*r)
        stc_info_label.pack()
        stc_info_button.pack()
        stc_lbl_pane.pack()
        stc_st_scale.pack()
        stc_decision_pane.pack(side="bottom", pady=10*r)
        #Einmaliges Aufnehmen eines Bildes, damit es in stc_lbl_pane angezeigt werden kann
        refresh_image()
        # Fenster bleibt bis zur manuellen Schließung geöffnet!
        stc_window.mainloop()
        
    #  Führe setup.py aus (Einrichtung und Kalibrierung des Einfallswinkels und der Wellenlängenskala)
    def setup_main_GUI():
        if GIF == True:
            t = threading.Thread(target=open_gif_main, name="Zeige GIF an") 
            t.daemon = True
            t.start()
        with open(Settings, "r") as sf:
            st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
        print("st=", st)
        if LED_connected == True:
            with open(Settings, "r") as sf:
                led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
            print("led=", led)
            if led == "100":
                GPIO.output(LED, GPIO.HIGH)
            else:
                t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
                t_led.daemon = True
                t_led.start()  
        setup_file_path = Speicherpfad + "/Setup_files/setup "
        tc = str("python3 " + Speicherpfad + "/Python_scripts/setup.py ")
        terminal_command = tc + setup_file_path + st 
        os.system(terminal_command)
        if LED_connected == True:
            if led is not "100":
                os.system("pkill -9 -f led.py")
            GPIO.output(LED, GPIO.LOW)
        os.system("pkill -9 -f gif_main.py") 
        os.system("pkill -9 -f setup.py")
      
    # Kalibrierung: Ablenkungswinkel des Optischen Gitters (Pop-up-Fenster)
    def spectrum_angle_calibration(event="2"):
        setup_window.withdraw()
        setup_main_GUI() #Wenn die alte Kalibrierung verworfen wird, muss hier erst einmal setup.py laufen, damit das Bild angezeigt werden kann
        sac_window = tk.Tk()
        sac_window.config(bg=bgc)
        sacw_width = 1650 * r
        sacw_height = 990 * r - int(ln(r) * 140)
        sacw_x = (screen_width/2) - (sacw_width/2)
        sacw_y = (screen_height/2) - (sacw_height/2)
        sac_window.geometry("%dx%d+%d+%d" % (sacw_width, sacw_height, sacw_x, sacw_y))
        sac_window.title("Lambda  |  Kalibrierung: Ablenkungswinkel")
        sacw_header = tk.Frame(sac_window, bg=hbg)
        sacw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        sacw_icon_image2 = sacw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        sacw_icon_image3 = ImageTk.PhotoImage(sacw_icon_image2, master=sac_window)
        sacw_icon_label = tk.Label(sacw_header, image=sacw_icon_image3, bg=hbg)
        sacw_icon_label.image = sacw_icon_image3
        sacw_icon_image.close()
        sacw_header_text = tk.Label(sacw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        sacw_header.pack(fill="x")
        sacw_icon_label.pack(side="left", padx=5*r)
        sacw_header_text.pack(side="right", padx=5*r)
        def update_spectrum_angle(): #Falls der Eintrag im Textfeld geändert wurde, wird die Information bei Ausführung dieser Funktion gespeichert.
            sa_new = spectrum_angle_entry.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[8] = "spectrum_angle = " + sa_new + "\n"
                sf.writelines(settings)
            print("sa_new=", sa_new)    
        def reset_sac(event="<Control-s>"):
            update_spectrum_angle()
            sac_window.destroy()
            spectrum_angle_calibration()
        def close_sac(event="<Control-f>"):
            sac_window.destroy()
            setup_window.deiconify()
            spectrum_angle_calibration_labelframe.config(fg="Gray65", font=labelfont)
            spectrum_scale_calibration_labelframe.config(fg=fgc, font=labelfont + " bold")
            spectrum_angle_calibration_button.config(text="Ablenkungswinkel kalibrieren \N{HEAVY CHECK MARK}", highlightbackground="green", state="disabled", font=labelfont)
            spectrum_scale_calibration_button.config(state="normal", font=labelfont)
            setup_sac_info.config(fg="Gray65", font=labelfont)
            setup_ssc_info.config(fg=fgc, font=labelfont)
        with open(Settings, "r") as sf:
            sa = sf.readlines()[8].lstrip("spectrum_angle = ").rstrip("\n")
        print("sa=", sa)
        # Widgets
        sac_info_string = ("Das linke Bild ist das eben aufgenommene, rechts findet sich ein Beispiel, "
                           "wie ein richtig kalibriertes Bild aussieht. Passen Sie den Winkel so "
                           "lange an, bis die Farbaufspaltungen so gut wie möglich innerhalb der Trennlinien liegen. Tragen Sie "
                           "dazu den neuen Winkel in das dafür vorgesehene Textfeld ein und klicken Sie auf "
                           "\"Winkel speichern und erneut kalibrieren\" oder drücken [Strg + S]. Sollen die Trennlinien nach unten "
                           "verschoben werden, so muss der Winkel verkleinert werden, nach oben muss er vergrößert "
                           "werden. Bei einem Winkel von 0° sind die Trennlinien exakt horizontal. "
                           "Es sind auch negative Winkel möglich! Mit einem Klick auf \"Fertig\" oder Drücken von [Strg + F] wird die Einrichtung abgeschlossen."
                          )
        sac_info = tk.Message(sac_window, width=1600*r, text=sac_info_string, bg=bgc, fg=fgc, font=labelfont)
        sac_result_pane = tk.PanedWindow(sac_window, bg=bgc)      
        sac_overlay_image = Image.open(Speicherpfad + "/Setup_files/setup_Overlay.jpg")
        sac_overlay_image2 = sac_overlay_image.resize((int(972*r), int(729*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        sac_overlay = ImageTk.PhotoImage(sac_overlay_image2, master=sac_result_pane)
        sac_overlay_label = tk.Label(sac_result_pane, image=sac_overlay, bg=bgc)
        sac_result_pane.add(sac_overlay_label)
        sac_example_image = Image.open(Speicherpfad + "/Images/sac_example.png")
        sac_example_image2 = sac_example_image.resize((int(648*r), int(486*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        sac_example = ImageTk.PhotoImage(sac_example_image2, master=sac_result_pane)
        sac_example_label = tk.Label(sac_result_pane, image=sac_example, bg=bgc)
        sac_result_pane.add(sac_example_label)        
        spectrum_angle_labelframe = tk.LabelFrame(sac_window, text="Winkel [°]:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
        spectrum_angle_entry = tk.Entry(spectrum_angle_labelframe, justify="center", font=labelfont, highlightbackground=bgc, bg=ebg, fg=efg, insertbackground=efg, selectbackground="green", selectforeground="white")
        spectrum_angle_entry.insert(0, sa)
        sac_warning = tk.Label(spectrum_angle_labelframe, text="ACHTUNG: Als Dezimalzeichen muss ein Punkt verwendet werden!", bg=bgc, fg=fgc, font=labelfont)
        sac_decision_pane = tk.PanedWindow(sac_window, bg=bgc)
        sac_failure = tk.Button(sac_decision_pane, text="Winkel speichern und erneut kalibrieren [Strg + S]", command=reset_sac, font=labelfont, bg="orange", activebackground="dark orange", activeforeground="black", highlightbackground=bgc)
        sac_window.bind("<Control-s>", reset_sac)
        sac_decision_pane.add(sac_failure)
        sac_success = tk.Button(sac_decision_pane, text="Fertig [Strg + F]", command=close_sac, font=labelfont, fg="white", bg="green", activebackground="dark green", activeforeground="white", highlightbackground=bgc)
        sac_window.bind("<Control-f>", close_sac)
        sac_decision_pane.add(sac_success)
        
        # Räumliche Anordnung der Widgets
        sac_info.pack()
        sac_result_pane.pack()
        spectrum_angle_labelframe.pack(padx=10*r, pady=10*r)
        spectrum_angle_entry.pack()
        sac_warning.pack()
        sac_decision_pane.pack(side="bottom", pady=10*r)
        # Fenster bleibt bis zur manuellen Schließung geöffnet!
        sac_window.mainloop()             
    
    # Kalibrierung: Faktor der Wellenlängenskala (Pop-up-Fenster)
    def spectrum_scale_calibration(event="3"):
        ssc_window = tk.Toplevel()
        ssc_window.config(bg=bgc)
        sscw_width = 500 * r
        sscw_height = 846 * r - int(ln(r) * 140)
        sscw_x = (screen_width/2) - (sscw_width/2)
        sscw_y = (screen_height/2) - (sscw_height/2)
        ssc_window.geometry("%dx%d+%d+%d" % (sscw_width, sscw_height, sscw_x, sscw_y))
        ssc_window.title("Lambda  |  Kalibrierung: Wellenlängenskala des Graphen")
        sscw_header = tk.Frame(ssc_window, bg=hbg)
        sscw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        sscw_icon_image2 = sscw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        sscw_icon_image3 = ImageTk.PhotoImage(sscw_icon_image2, master=ssc_window)
        sscw_icon_label = tk.Label(sscw_header, image=sscw_icon_image3, bg=hbg, font=labelfont)
        sscw_icon_label.image = sscw_icon_image3
        sscw_icon_image.close()
        sscw_header_text = tk.Label(sscw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        sscw_header.pack(fill="x")
        sscw_icon_label.pack(side="left", padx=5*r)
        sscw_header_text.pack(side="right", padx=5*r)
        setup_window.withdraw()
        def update_spectrum_scale(): #Falls der Eintrag im Textfeld geändert wurde, wird die Information bei Ausführung dieser Funktion gespeichert.
            ss_new = spectrum_scale_entry.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[9] = "spectrum_scale = " + ss_new + "\n"
                sf.writelines(settings)
            print("ss_new=", ss_new)
        def reset_ssc(event="<Control-s>"):
            update_spectrum_scale()
            ssc_window.withdraw()
            setup_main_GUI()
            spectrum_scale_calibration()            
        def close_ssc(event="<Control-f>"):
            ssc_window.destroy()
            setup_window.deiconify()
            setup_close_button.config(text="Einrichtung abgeschlossen! Sie können das Spektrometer nun verwenden! \n Klicken Sie hier oder drücken Sie [Esc] um das Fenster zu schließen.", font=labelfont, bg="green", activebackground="dark green", activeforeground="white")
            spectrum_scale_calibration_labelframe.config(fg="Gray65", font=labelfont)
            spectrum_scale_calibration_button.config(text="Wellenlängenskala des Graphen kalibrieren \N{HEAVY CHECK MARK}", highlightbackground="green", state="disabled", font=labelfont)
            setup_ssc_info.config(fg="Gray65", font=labelfont)
        with open(Settings, "r") as sf:
            ss = sf.readlines()[9].lstrip("spectrum_scale = ").rstrip("\n")
        print("ss=", ss)
        # Widgets
        ssc_info_string = ("Suchen Sie in der untenstehenden Tabelle die bekannte Wellenlänge, die die Lichtquelle emittiert. "
                           "Deren Intensität sollte bei 100 % oder so nahe wie möglich daneben liegen. Tut sie dies nicht, "
                           "passen Sie den Faktor der Wellenlängenskala im untenstehenden Textfeld an und klicken Sie auf "
                           "\"Faktor speichern und erneut kalibrieren\" oder drücken [Strg + S]. Liegt das Maximum bei einer zu niedrigen "
                           "Wellenlänge, so muss der Faktor erhöht, andernfalls verringert werden. "
                           "Mit einem Klick auf \"Fertig\" oder Drücken von [Strg + F] wird die Einrichtung abgeschlossen."
                          )
        ssc_info = tk.Message(ssc_window, width=480*r, text=ssc_info_string, bg=bgc, fg=fgc, font=labelfont)
        #Tabellenframe
        ssc_csv = tk.Frame(ssc_window)
        scrollbary = tk.Scrollbar(ssc_csv, orient="vertical", width=26*r, bg=bgc, highlightbackground=bgc, activebackground=abc, troughcolor=bgc)
        table = ttk.Treeview(ssc_csv, columns=("w", "a"), height=int(25*r), selectmode="extended", yscrollcommand=scrollbary.set)
        scrollbary.config(command=table.yview)
        scrollbary.pack(side="right", fill="y")
        def scroll_down(event="<Down>"):
            new_position0 = scrollbary.get()[0] + 0.01
            new_position1 = scrollbary.get()[1] + 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        def scroll_up(event="<Up>"):
            new_position0 = scrollbary.get()[0] - 0.01
            new_position1 = scrollbary.get()[1] - 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        ssc_window.bind("<Down>", scroll_down)
        ssc_window.bind("<Up>", scroll_up)
        nametofont("TkHeadingFont").configure(size=int(10*r))
        table.heading("w", text="Wellenlänge [nm]", anchor="w")
        table.heading("a", text="Intensität [%]", anchor="w")
        table.column("#0", stretch="no", minwidth=0, width=0)
        table.column("#1", stretch="no", minwidth=0, width=int(150*r))
        table.column("#2", stretch="no", minwidth=0, width=int(150*r))
        
        with open(Settings, "r") as sf:
            csv_mode = sf.readlines()[10].lstrip("csv_mode = ").rstrip("\n")
        print("csv_mode=", csv_mode)
        with open(Speicherpfad + "/Setup_files/setup.csv") as f:
            if csv_mode == "English":
                reader = csv.DictReader(f, delimiter=",")
            else:
                reader = csv.DictReader(f, delimiter=";")
            for row in reader:
                w = row["Wellenlänge [nm]"]
                a = row["Intensität [%]"]
                table.insert("", 0, values=(w, a), tags="table_entries")
                table.tag_configure("table_entries", font=labelfont)
        #Rest der Widgets        
        spectrum_scale_labelframe = tk.LabelFrame(ssc_window, text="Faktor der Wellenlängenskala:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
        spectrum_scale_entry = tk.Entry(spectrum_scale_labelframe, justify="center", font=labelfont, highlightbackground=bgc, bg=ebg, fg=efg, insertbackground=efg, selectbackground="green", selectforeground="white")
        spectrum_scale_entry.insert(0, ss)
        ssc_warning = tk.Label(spectrum_scale_labelframe, text="ACHTUNG: Als Dezimalzeichen muss ein Punkt verwendet werden!", bg=bgc, fg=fgc, font=labelfont)
        ssc_decision_pane = tk.PanedWindow(ssc_window, bg=bgc)
        ssc_failure = tk.Button(ssc_decision_pane, text="Faktor speichern und erneut kalibrieren [Strg + S]", command=reset_ssc, font=labelfont, bg="orange", activebackground="dark orange", activeforeground="black", highlightbackground=bgc)
        ssc_window.bind("<Control-s>", reset_ssc)
        ssc_decision_pane.add(ssc_failure)
        ssc_success = tk.Button(ssc_decision_pane, text="Fertig [Strg + F]", command=close_ssc, font=labelfont, fg="white", bg="green", activebackground="dark green", activeforeground="white", highlightbackground=bgc)
        ssc_window.bind("<Control-f>", close_ssc)
        ssc_decision_pane.add(ssc_success)
        # Räumliche Anordnung der Widgets
        ssc_info.pack()
        ssc_csv.pack(side="top")
        table.pack()
        spectrum_scale_labelframe.pack(padx=10*r, pady=10*r)
        spectrum_scale_entry.pack()
        ssc_warning.pack()
        ssc_decision_pane.pack(side="bottom", pady=10*r)
        # Fenster bleibt bis zur manuellen Schließung geöffnet!    
        ssc_window.mainloop()
    
    # Widgets
    setup_welcome = tk.Label(setup_window, text="Willkommen beim Einrichtungs-Assistenten!", anchor="sw", font=labelfont + " bold", justify="left", bg=bgc, fg=fgc)
    setup_shutter_time_calibration_labelframe = tk.LabelFrame(setup_window, text="1. Schritt:", padx=5*r, pady=5*r, font=labelfont + " bold", bg=bgc, fg=fgc)
    setup_shutter_time_calibration_button = tk.Button(setup_shutter_time_calibration_labelframe, text="Verschlusszeit kalibrieren [1]", command=setup_shutter_time_calibration, font=labelfont,
                                                      bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    setup_window.bind("1", setup_shutter_time_calibration)
    setup_stc_info_string = ("Wählen Sie eine Lichtquelle, deren emittierte Wellenlänge(n) Ihnen bekannt sind, "
                             "z.B. einen Laser oder eine spezielle LED. "
                             "Stellen Sie sicher, dass die Lichtquelle eingeschaltet und vor dem Spektrometer "
                             "positioniert ist. Verändern Sie den Aufbau während der Einrichtung nicht!"
                            )
    setup_stc_info = tk.Message(setup_shutter_time_calibration_labelframe, width=500*r, text=setup_stc_info_string, justify="left", bg=bgc, fg=fgc, font=labelfont)
    spectrum_angle_calibration_labelframe = tk.LabelFrame(setup_window, text="2. Schritt:", padx=5*r, pady=5*r, fg="Gray65", bg=bgc, font=labelfont)
    spectrum_angle_calibration_button = tk.Button(spectrum_angle_calibration_labelframe, text="Ablenkungswinkel kalibrieren [2]", command=spectrum_angle_calibration, state="disabled",
                                                  bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    setup_window.bind("2", spectrum_angle_calibration)
    setup_sac_info_string = ("Je nachdem, wie die Beugungsfolie angebracht wurde, "
                             "ist der Winkel in dem das Licht aufgebrochen wird unterschiedlich. "
                             "Dieser Winkel wird hier eingestellt."
                            )
    setup_sac_info = tk.Message(spectrum_angle_calibration_labelframe, width=500*r, text=setup_sac_info_string, fg="Gray65", justify="left", bg=bgc, font=labelfont)    
    spectrum_scale_calibration_labelframe = tk.LabelFrame(setup_window, text="3. Schritt:", padx=5*r, pady=5*r, fg="Gray65", bg=bgc, font=labelfont)
    spectrum_scale_calibration_button = tk.Button(spectrum_scale_calibration_labelframe, text="Wellenlängenskala des Graphen kalibrieren [3]", command=spectrum_scale_calibration, font=labelfont,
                                                  state="disabled", bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    setup_window.bind("3", spectrum_scale_calibration)
    setup_ssc_info_string = ("Je nachdem, welche Art Beugungsfolie angebracht wurde, "
                             "wird das Licht unterschiedlich weit aufgebrochen, bevor es "
                             "auf die Kameralinse trifft. Der Faktor, über den die detektierten "
                             "Farbsignale den Wellenlängen zugeordnet werden, wird hier eingestellt."
                            )
    setup_ssc_info = tk.Message(spectrum_scale_calibration_labelframe, width=500*r, text=setup_ssc_info_string, fg="Gray65", justify="left", bg=bgc, font=labelfont)     
    def setup_close(event="<Escape>"):
        root.deiconify() 
        setup_window.destroy()
    setup_close_button = tk.Button(setup_window, text="Einrichtung abbrechen [Esc]", command=setup_close, font=labelfont, bg="red", fg="white", activebackground="red3", activeforeground="white", highlightbackground=bgc)
    setup_window.bind("<Escape>", setup_close)
    
    # Räumliche Anordnung der Widgets
    setup_welcome.pack(fill="x")
    setup_shutter_time_calibration_labelframe.pack(padx=10*r, pady=10*r)
    setup_stc_info.pack()
    setup_shutter_time_calibration_button.pack()    
    spectrum_angle_calibration_labelframe.pack(padx=10*r, pady=10*r)
    setup_sac_info.pack()
    spectrum_angle_calibration_button.pack()    
    spectrum_scale_calibration_labelframe.pack(padx=10*r, pady=10*r)
    setup_ssc_info.pack()
    spectrum_scale_calibration_button.pack()
    setup_close_button.pack(side="bottom", pady=5*r)
    # Fenster bleibt bis zur manuellen Schließung geöffnet! 
    setup_window.mainloop()




# Live-Kamera
def preview_start(event="<Control-k>"):
    if LED_connected == True:
        GPIO.output(LED, GPIO.HIGH)
    global camera
    camera = PiCamera()
    camera.rotation = 90
    camera.vflip = True
    camera.iso = 100
    camera.exposure_mode = "off"
    camera.awb_mode = "off"
    camera.awb_gains = (1, 1)
    camera.start_preview(alpha=220)
    settings_button.config(state="disabled")
    about_button.config(state="disabled")
    help_button.config(state="disabled")
    info_button1.config(state="disabled")
    info_button2.config(state="disabled")
    camera_button.config(bg="red", fg="white", font="TkDefaultFont " + str(int(50*r)) + " bold", state="normal", command=preview_stop, text="Live-Kamera stoppen [Esc]", activebackground="red3", activeforeground="white")
    setup_button.config(state="disabled")
    path_entry.config(state="disabled")
    directory_button.config(state="disabled")
    reset_button.config(bg=bgc, fg=fgc, state="disabled")
    reference_window_button.config(state="disabled")
    main_button.config(state="disabled")
    raw_button.config(state="disabled")
    out_button.config(state="disabled")
    chart_button.config(state="disabled")
    csv_button.config(state="disabled")
    series_button.config(state="disabled")
    close_button.config(bg=bgc, fg=fgc, state="disabled")
    root.bind("<Escape>", preview_stop)
    root.geometry("%dx%d+%d+%d" % (screen_width - int(200*r), height + int(100*r), screen_width/2 - (screen_width - int(200*r))/2, y))
def preview_stop(event="<Escape>"):
    camera.stop_preview()
    camera.close()
    if LED_connected == True:
        GPIO.output(LED, GPIO.LOW)
    settings_button.config(state="normal")
    about_button.config(state="normal")
    help_button.config(state="normal")
    info_button1.config(state="normal")
    info_button2.config(state="normal")
    camera_button.config(bg=bgc, fg=fgc, font=labelfont, text="Live-Kamera starten [Strg + K]", command=preview_start, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    setup_button.config(state="normal")
    path_entry.config(state="normal")
    directory_button.config(state="normal")
    reset_button.config(bg="green", fg="white", state="normal", activebackground="dark green", activeforeground="white")
    reference_window_button.config(state="normal")
    main_button.config(state="normal")
    raw_button.config(state="normal")
    out_button.config(state="normal")
    chart_button.config(state="normal")
    csv_button.config(state="normal")
    close_button.config(bg="red", fg="white", state="normal", activebackground="red3", activeforeground="white")
    series_button.config(state="normal")
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))




# Referenzmessung
def reference(event="<F2>"):
    root.withdraw()
    reference_window = tk.Tk()
    reference_window.config(bg=bgc)
    refw_width = 854 * r - int(ln(r) * 140)
    refw_height = 516 * r - int(ln(r) * 180)
    refw_x = (screen_width/2) - (refw_width/2)
    refw_y = (screen_height/2) - (refw_height/2)
    reference_window.geometry("%dx%d+%d+%d" % (refw_width, refw_height, refw_x, refw_y))
    refw_header = tk.Frame(reference_window, bg=hbg)
    refw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    refw_icon_image2 = refw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    refw_icon_image3 = ImageTk.PhotoImage(refw_icon_image2, master=reference_window)
    refw_icon_label = tk.Label(refw_header, image=refw_icon_image3, bg=hbg)
    refw_icon_label.image = refw_icon_image3
    refw_icon_image.close()
    refw_header_text = tk.Label(refw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    refw_header.pack(fill="x")
    refw_icon_label.pack(side="left", padx=5*r)
    refw_header_text.pack(side="right", padx=5*r)
    reference_window.title("Lambda  |  Referenzmessung")
    def reference_close(event="<Escape>"):
        reference_window.destroy()
        root.deiconify()

    # Kalibrierung: Verschlusszeit (Pop-up-Fenster)
    def shutter_time_calibration(event="1"):
        stc_window = tk.Toplevel()
        stc_window.config(bg=bgc)
        stcw_width = 800 * r
        stcw_height = 860 * r - int(ln(r) * 140)
        stcw_x = (screen_width/2) - (stcw_width/2)
        stcw_y = (screen_height/2) - (stcw_height/2)
        stc_window.geometry("%dx%d+%d+%d" % (stcw_width, stcw_height, stcw_x, stcw_y))
        stc_window.title("Lambda  |  Kalibrierung: Verschlusszeit der Kamera und Helligkeit der LED")
        stc_header = tk.Frame(stc_window, bg=hbg)
        stc_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        stc_icon_image2 = stc_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        stc_icon_image3 = ImageTk.PhotoImage(stc_icon_image2, master=stc_window)
        stc_icon_label = tk.Label(stc_header, image=stc_icon_image3, bg=hbg)
        stc_icon_label.image = stc_icon_image3
        stc_icon_image.close()
        stc_header_text = tk.Label(stc_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        stc_header.pack(fill="x")
        stc_icon_label.pack(side="left", padx=5*r)
        stc_header_text.pack(side="right", padx=5*r)
        reference_window.withdraw()
        with open(Settings, "r") as sf:
            led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
        print("led=", led)
        with open(Settings, "r") as sf:
            st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
        print("st=", st)
        def take_new_picture():
            stc_window.withdraw()
            st_new = stc_st_scale.get()
            led_new = stc_led_scale.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[6] = "LED_brightness = " + str(led_new) + "\n"
                settings[7] = "shutter_time = " + str(st_new) + "\n"
                sf.writelines(settings)
            print("led_new=", led_new)
            print("st_new=", st_new)
            if LED_connected == True:
                if led_new == 100:
                    GPIO.output(LED, GPIO.HIGH)
                else:
                    t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
                    t_led.daemon = True
                    t_led.start()            
            setup_file_path = Speicherpfad + "/Setup_files/setup "
            tc = str("python3 " + Speicherpfad + "/Python_scripts/calibration.py ")
            terminal_command = tc + setup_file_path + str(int(stc_st_scale.get())) 
            os.system(terminal_command)
            if LED_connected == True: 
                if led_new is not 100:
                    os.system("pkill -9 -f led.py")
                GPIO.output(LED, GPIO.LOW)
            stc_window.deiconify()
        def refresh_image(event="n"):
            if GIF == True:
                t = threading.Thread(target=open_gif_main, name="Zeige GIF an") 
                t.daemon = True
                t.start()
            take_new_picture()
            os.system("pkill -9 -f gif_main.py")
            os.system("pkill -9 -f calibration.py")
            stc_lbl_image_new = Image.open(Speicherpfad + "/Setup_files/setup_Bild.jpg")
            stc_lbl_image2_new = stc_lbl_image_new.resize((int(648*r), int(486*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            stc_lbl_image3_new = ImageTk.PhotoImage(stc_lbl_image2_new, master=stc_window)
            stc_lbl.config(image=stc_lbl_image3_new)
            stc_lbl.image = stc_lbl_image3_new
            stc_lbl_image_new.close() 
        def stc_examples(event="b"): 
            stc_examples_window = tk.Tk()
            stc_examples_window.config(bg=bgc)
            stc_examples_w_width = 1454 * r
            stc_examples_w_height = 440 * r - int(ln(r) * 140)
            stc_examples_w_x = (screen_width/2) - (stc_examples_w_width/2)
            stc_examples_w_y = (screen_height/2) - (stc_examples_w_height/2)
            stc_examples_window.geometry("%dx%d+%d+%d" % (stc_examples_w_width, stc_examples_w_height, stc_examples_w_x, stc_examples_w_y))
            stc_examples_window.title("Lambda  |  Kalibrierung: Verschlusszeit der Kamera und Helligkeit der LED (Beispielbilder)")
            stc_examples_header = tk.Frame(stc_examples_window, bg=hbg)
            stc_examples_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
            stc_examples_icon_image2 = stc_examples_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            stc_examples_icon_image3 = ImageTk.PhotoImage(stc_examples_icon_image2, master=stc_examples_window)
            stc_examples_icon_label = tk.Label(stc_examples_header, image=stc_examples_icon_image3, bg=hbg)
            stc_examples_icon_label.image = stc_examples_icon_image3
            stc_examples_icon_image.close()
            stc_examples_header_text = tk.Label(stc_examples_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
            stc_examples_header.pack(fill="x")
            stc_examples_icon_label.pack(side="left", padx=5*r)
            stc_examples_header_text.pack(side="right", padx=5*r)
            def stc_examples_close(event="<Escape>"):
                stc_examples_window.destroy()
            #Widgets
            example_image = Image.open(Speicherpfad + "/Images/stc_example.png")
            example_image2 = example_image.resize((int(1450*r), int(338*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
            example_image3 = ImageTk.PhotoImage(example_image2, master=stc_examples_window)
            example_label = tk.Label(stc_examples_window, image=example_image3, bg=bgc)    
            stc_examples_close_button = tk.Button(stc_examples_window, text="Fenster schließen [Esc]", bg="red", fg="white", command=stc_examples_close, font=labelfont, activebackground="red3", activeforeground="white", highlightbackground=bgc)
            stc_examples_window.bind("<Escape>", stc_examples_close)
            #Anordnung der Widgets
            example_label.pack(pady=5*r)
            stc_examples_close_button.pack(side="bottom", pady=10*r)    
            stc_examples_window.mainloop()
        def abort_stc(event="<Escape>"):
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[6] = "LED_brightness = " + str(led) + "\n"
                settings[7] = "shutter_time = " + str(st) + "\n"
                sf.writelines(settings)
            print("led=", led)
            print("st=", st)
            stc_window.destroy()
            reference_window.deiconify()
            os.system("pkill -9 -f led.py")
        def close_stc(event="s"):
            led_new = stc_led_scale.get()
            st_new = stc_st_scale.get()
            with open(Settings, "r") as sf:
                settings = sf.readlines()
            with open(Settings, "w") as sf:
                settings[6] = "LED_brightness = " + str(led_new) + "\n"
                settings[7] = "shutter_time = " + str(st_new) + "\n"
                sf.writelines(settings)
            print("led_new=", led_new)
            print("st_new=", st_new) 
            stc_window.destroy()
            reference_window.deiconify()
            os.system("pkill -9 -f led.py")
            shutter_time_calibration_button.config(text="Verschlusszeit erneut kalibrieren [1]", fg=fgc)
            reference_button.config(fg=blu)
            
        # Hinweise
        stc_info_labelframe = tk.LabelFrame(stc_window, text="Hinweise:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
        stc_info_string = ("Damit das Programm optimal arbeiten kann, darf die Helligkeit des aufgenommenen Bildes nicht zu hoch sein. "
                               "Passen Sie dafür rechts die Helligkeit der LED (in Prozent) und/oder unten die Verschlusszeit der Kamera "
                               "(in Mikrosekunden) an (Ersteres kann ignoriert werden, "
                               "falls für den Aufbau des Spektrometers keine LED an den RaspberryPi angeschlossen wurde, sondern eine externe "
                               "Lichtquelle verwendet wird. Es wird empfohlen, nur die Verschlusszeit zu ändern und die LED auf 100 % "
                               "Intensität zu lassen, da durch das Dimmen Ressourcen des RaspberryPi belegt werden. "
                               "Für eine Anleitung eines Beilspielaufbaus eines Low-Cost Spektrometers klicken Sie "
                               "im Hauptfenster auf \"Hilfe\") \n"
                               "Unter \"Beispiele\" sind Beispielbilder abgebildet, die Ihnen zeigen, welche Helligkeit optimal ist. "
                               "Das folgende Bild wird durch Klicken auf \"Neues Bild aufnehmen\" oder Drücken von [N] aktualisiert!"
                              )
        stc_info_label = tk.Message(stc_info_labelframe, bg=bgc, fg=fgc, justify="left", width=int(750*r), font=labelfont, text=stc_info_string)
        stc_info_button = tk.Button(stc_info_labelframe, text="Beispiele [B]", bg=bgc, fg=fgc, command=stc_examples, font=labelfont, activebackground=abc, activeforeground=fgc, highlightbackground=bgc)
        stc_window.bind("b", stc_examples)
        # Bild
        stc_lbl_pane = tk.PanedWindow(stc_window, bg=bgc)
        stc_lbl_image = Image.open(Speicherpfad + "/Setup_files/setup_Bild.jpg")
        stc_lbl_image2 = stc_lbl_image.resize((int(648*r), int(486*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        stc_lbl_image3 = ImageTk.PhotoImage(stc_lbl_image2, master=stc_window)
        stc_lbl = tk.Label(stc_window, image=stc_lbl_image3)
        stc_lbl_image.close()
        stc_lbl_pane.add(stc_lbl)
        # Helligkeits-Slider
        stc_led_scale = tk.Scale(stc_window, from_=100, to=0, bg=bgc, activebackground=abc, font=labelfont, fg=fgc,
                                 highlightbackground=bgc, troughcolor=ebg)
        stc_led_scale.set(float(led))
        stc_lbl_pane.add(stc_led_scale)
        def move_up(event="<Up>"):
            led_new = stc_led_scale.get()
            stc_led_scale.set(led_new + 1)
        def move_down(event="<Down>"):
            led_new = stc_led_scale.get()
            stc_led_scale.set(led_new - 1)
        stc_window.bind("<Up>", move_up)
        stc_window.bind("<Down>", move_down)
        # Verschlusszeit-Slider
        stc_st_scale = tk.Scale(stc_window, from_=1000, to=200000, orient="horizontal", length=int(700*r), 
                                bg=bgc, activebackground=abc, font=labelfont, fg=fgc, highlightbackground=bgc, troughcolor=ebg)
        stc_st_scale.set(st)
        def move_left(event="<Left>"):
            st_new = stc_st_scale.get()
            stc_st_scale.set(round(st_new, -3) - 1000)
        def move_right (event="<Right>"):
            st_new = stc_st_scale.get()
            stc_st_scale.set(round(st_new, -3) + 1000)
        stc_window.bind("<Left>", move_left)
        stc_window.bind("<Right>", move_right)
        # Zurück- und Schließen-Buttons
        stc_decision_pane = tk.PanedWindow(stc_window, bg=bgc)
        stc_back = tk.Button(stc_decision_pane, text="Zurück und Änderungen verwerfen [Esc]", command=abort_stc, font=labelfont, fg="white", bg="red", activebackground="red3", activeforeground="white", highlightbackground=bgc)
        stc_window.bind("<Escape>", abort_stc)
        stc_decision_pane.add(stc_back)
        stc_renew = tk.Button(stc_decision_pane, text="Neues Bild aufnehmen [N]", command=refresh_image, font=labelfont, bg="orange", activebackground="dark orange", activeforeground="black", highlightbackground=bgc)
        stc_window.bind("n", refresh_image)
        stc_decision_pane.add(stc_renew)
        stc_success = tk.Button(stc_decision_pane, text="Speichern und weiter [S]", command=close_stc, font=labelfont, fg="white", bg="green", activebackground="dark green", activeforeground="white", highlightbackground=bgc)
        stc_window.bind("s", close_stc)
        stc_decision_pane.add(stc_success)
        
        #Räumliche Anordnung der Widgets
        stc_info_labelframe.pack(padx=10*r, pady=10*r)
        stc_info_label.pack()
        stc_info_button.pack()
        stc_lbl_pane.pack()
        stc_st_scale.pack()
        stc_decision_pane.pack(side="bottom", pady=10*r)
        #Einmaliges Aufnehmen eines Bildes, damit es in stc_lbl_pane angezeigt werden kann
        refresh_image()
        # Fenster bleibt bis zur manuellen Schließung geöffnet!
        stc_window.mainloop()
        
    # Hauptprogramm (Angepasst für Referenzmessung)
    def reference_main_GUI(event="2"):
        reference_window.withdraw()
        if GIF == True:
            t = threading.Thread(target=open_gif_main, name="Zeige GIF an")
            t.daemon = True
            t.start()
        with open(Settings, "r") as sf:
            st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
        print("st=", st)
        if LED_connected == True:
            with open(Settings, "r") as sf:
                led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
            print("led=", led)
            if led == "100":
                GPIO.output(LED, GPIO.HIGH)
            else:
                t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
                t_led.daemon = True
                t_led.start()
        reference_file_path = Speicherpfad + "/Reference_files/reference "
        tc = str("python3 " + Speicherpfad + "/Python_scripts/reference.py ")
        terminal_command = tc + reference_file_path + st 
        os.system(terminal_command)
        if LED_connected == True:
            if led is not "100":
                os.system("pkill -9 -f led.py")
            GPIO.output(LED, GPIO.LOW)
        os.system("pkill -9 -f gif_main.py")
        os.system("pkill -9 -f reference.py")
        reference_button.config(text="Neue Referenzmessung starten und alte überschreiben [2]", fg=fgc)
        shutter_time_calibration_button.config(fg=fgc)
        reference_window_close_button.config(text="Schließen und zurück zum Hauptfenster [Esc]", bg="green", fg="white", activebackground="dark green", activeforeground="white")
        reference_window.deiconify()
        
    # Ergebnisse der Referenzmessung anzeigen
    def display_ref_raw(event="<F5>"):
        ref_raw_window = tk.Tk()
        ref_raw_window.config(bg=bgc)
        ref_raww_width = 1300 * r
        ref_raww_height = 1005 * r
        ref_raww_x = (screen_width/2) - (ref_raww_width/2)
        ref_raww_y = (screen_height/2) - (ref_raww_height/2)
        ref_raw_window.geometry("%dx%d+%d+%d" % (ref_raww_width, ref_raww_height, ref_raww_x, ref_raww_y))
        ref_raww_header = tk.Frame(ref_raw_window, bg=hbg)
        ref_raww_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ref_raww_icon_image2 = ref_raww_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ref_raww_icon_image3 = ImageTk.PhotoImage(ref_raww_icon_image2, master=ref_raw_window)
        ref_raww_icon_label = tk.Label(ref_raww_header, image=ref_raww_icon_image3, bg=hbg)
        ref_raww_icon_label.image = ref_raww_icon_image3
        ref_raww_icon_image.close()
        ref_raww_header_text = tk.Label(ref_raww_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ref_raww_header.pack(fill="x")
        ref_raww_icon_label.pack(side="left", padx=5*r)
        ref_raww_header_text.pack(side="right", padx=5*r)
        ref_raw_image = Image.open(Speicherpfad + "/Reference_files/reference_Bild.jpg")
        ref_raw_image2 = ref_raw_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust        
        ref_raw_image3 = ImageTk.PhotoImage(ref_raw_image2, master=ref_raw_window)
        ref_raw_label = tk.Label(ref_raw_window, image=ref_raw_image3, bg=bgc)
        ref_raw_label.pack()
        ref_raw_window.title("Lambda  |  Bild (Referenzmessung)")
        def esc(event="<Escape>"):
            ref_raw_window.destroy()
        ref_raw_window.bind("<Escape>", esc)
        ref_raw_window.mainloop()
    def display_ref_out(event="<F6>"):
        ref_out_window = tk.Tk()
        ref_out_window.config(bg=bgc)
        ref_outw_width = 1300 * r
        ref_outw_height = 1005 * r
        ref_outw_x = (screen_width/2) - (ref_outw_width/2)
        ref_outw_y = (screen_height/2) - (ref_outw_height/2)
        ref_out_window.geometry("%dx%d+%d+%d" % (ref_outw_width, ref_outw_height, ref_outw_x, ref_outw_y))
        ref_outw_header = tk.Frame(ref_out_window, bg=hbg)
        ref_outw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ref_outw_icon_image2 = ref_outw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ref_outw_icon_image3 = ImageTk.PhotoImage(ref_outw_icon_image2, master=ref_out_window)
        ref_outw_icon_label = tk.Label(ref_outw_header, image=ref_outw_icon_image3, bg=hbg)
        ref_outw_icon_label.image = ref_outw_icon_image3
        ref_outw_icon_image.close()
        ref_outw_header_text = tk.Label(ref_outw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ref_outw_header.pack(fill="x")
        ref_outw_icon_label.pack(side="left", padx=5*r)
        ref_outw_header_text.pack(side="right", padx=5*r)        
        ref_out_image = Image.open(Speicherpfad + "/Reference_files/reference_Overlay.jpg")
        ref_out_image2 = ref_out_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
        ref_out_image3 = ImageTk.PhotoImage(ref_out_image2, master=ref_out_window)
        ref_out_label = tk.Label(ref_out_window, image=ref_out_image3, bg=bgc)
        ref_out_label.pack()
        ref_out_window.title("Lambda  |  Bild mit Overlay (Referenzmessung)")
        def esc(event="<Escape>"):
            ref_out_window.destroy()
        ref_out_window.bind("<Escape>", esc)
        ref_out_window.mainloop()
    def display_ref_chart(event="<F7>"):
        ref_chart_window = tk.Tk()
        ref_chart_window.config(bg=bgc)
        ref_chartw_width = 1264 * r
        ref_chartw_height = 655 * r
        ref_chartw_x = (screen_width/2) - (ref_chartw_width/2)
        ref_chartw_y = (screen_height/2) - (ref_chartw_height/2)
        ref_chart_window.geometry("%dx%d+%d+%d" % (ref_chartw_width, ref_chartw_height, ref_chartw_x, ref_chartw_y))
        ref_chartw_header = tk.Frame(ref_chart_window, bg=hbg)
        ref_chartw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ref_chartw_icon_image2 = ref_chartw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ref_chartw_icon_image3 = ImageTk.PhotoImage(ref_chartw_icon_image2, master=ref_chart_window)
        ref_chartw_icon_label = tk.Label(ref_chartw_header, image=ref_chartw_icon_image3, bg=hbg)
        ref_chartw_icon_label.image = ref_chartw_icon_image3
        ref_chartw_icon_image.close()
        ref_chartw_header_text = tk.Label(ref_chartw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ref_chartw_header.pack(fill="x")
        ref_chartw_icon_label.pack(side="left", padx=5*r)
        ref_chart_image = Image.open(Speicherpfad + "/Reference_files/reference_Spektrum.png")
        ref_chart_image2 = ref_chart_image.resize((int(1260*r), int(620*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
        ref_chart_image3 = ImageTk.PhotoImage(ref_chart_image2, master=ref_chart_window)
        ref_chart_label = tk.Label(ref_chart_window, image=ref_chart_image3, bg=bgc)
        ref_chart_label.pack()
        ref_chart_window.title("Lambda  |  Intensitätsspektrum (Referenzmessung)")
        def esc(event="<Escape>"):
            ref_chart_window.destroy()
        ref_chart_window.bind("<Escape>", esc)
        ref_chart_window.mainloop()
    def display_ref_csv(event="<F8>"):
        ref_csv_window = tk.Toplevel()
        ref_csv_window.config(bg=bgc)
        ref_csv_window.resizable(0, 0)
        ref_csvw_width = 436 * r
        ref_csvw_height = 855 * r
        ref_csvw_x = (screen_width/2) - (ref_csvw_width/2)
        ref_csvw_y = (screen_height/2) - (ref_csvw_height/2)
        ref_csv_window.geometry("%dx%d+%d+%d" % (ref_csvw_width, ref_csvw_height, ref_csvw_x, ref_csvw_y))
        ref_csvw_header = tk.Frame(ref_csv_window, bg=hbg)
        ref_csvw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ref_csvw_icon_image2 = ref_csvw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ref_csvw_icon_image3 = ImageTk.PhotoImage(ref_csvw_icon_image2, master=ref_csv_window) 
        ref_csvw_icon_label = tk.Label(ref_csvw_header, image=ref_csvw_icon_image3, bg=hbg)
        ref_csvw_icon_label.image = ref_csvw_icon_image3 
        ref_csvw_icon_image.close()
        ref_csvw_header_text = tk.Label(ref_csvw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ref_csvw_header.pack(fill="x")
        ref_csvw_icon_label.pack(side="left", padx=5*r)
        ref_csvw_header_text.pack(side="right", padx=5*r)
        scrollbary = tk.Scrollbar(ref_csv_window, orient="vertical", width=26*r, bg=bgc, highlightbackground=bgc, activebackground=abc, troughcolor=bgc) #default: width=16
        table = ttk.Treeview(ref_csv_window, columns=("w", "i0"), height=int(40*r), selectmode="extended", yscrollcommand=scrollbary.set)
        scrollbary.config(command=table.yview)
        scrollbary.pack(side="right", fill="y")
        def scroll_down(event="<Down>"):
            new_position0 = scrollbary.get()[0] + 0.01
            new_position1 = scrollbary.get()[1] + 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        def scroll_up(event="<Up>"):
            new_position0 = scrollbary.get()[0] - 0.01
            new_position1 = scrollbary.get()[1] - 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        ref_csv_window.bind("<Down>", scroll_down)
        ref_csv_window.bind("<Up>", scroll_up)
        nametofont("TkHeadingFont").configure(size=int(10*r))
        table.heading("w", text="Wellenlänge [nm]", anchor="w")
        table.heading("i0", text="Intensität (Referenzmessung)", anchor="w")
        table.column("#0", stretch="no", minwidth=0, width=0)
        table.column("#1", stretch="no", minwidth=0, width=int(150*r))
        table.column("#2", stretch="no", minwidth=0, width=int(250*r))
        ref_csv_path = Speicherpfad + "/Reference_files/reference.csv"
        with open(Settings, "r") as sf:
            csv_mode = sf.readlines()[10].lstrip("csv_mode = ").rstrip("\n")
        print("csv_mode=", csv_mode)
        with open(ref_csv_path) as f:
            if csv_mode == "English":
                reader = csv.DictReader(f, delimiter=",")
            else:
                reader = csv.DictReader(f, delimiter=";")
            for row in reader:
                w = row["Wellenlänge [nm]"]
                i0 = row["Intensität (Referenzmessung)"]
                table.insert("", 0, values=(w, i0), tags="table_entries")
                table.tag_configure("table_entries", font=labelfont)
        table.pack()
        ref_csv_window.title(ref_csv_path)
        def esc(event="<Escape>"):
            ref_csv_window.destroy()
        ref_csv_window.bind("<Escape>", esc)
        ref_csv_window.mainloop()
                
    #Widgets
    ref_cal_labelframe = tk.LabelFrame(reference_window, text="1.:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ref_cal_info_string = ("Damit das Spektrum richtig ausgewertet werden kann ist es wichtig, dass die Verschlusszeit der Kamera "
                           "an die Helligkeit der Lichtquelle angepasst ist. Platzieren Sie hierzu die Lichtquelle und die "
                           "Referenzprobe, z.B. destilliertes Wasser, vor dem Spalt und klicken Sie auf \"Verschlusszeit "
                           "kalibrieren\" oder drücken [1]. Um die Verschlusszeit - falls nötig - anzupassen folgen Sie "
                           "den weiteren Anweisungen."
                           "                                                                                                      "
                           "                                                                                                      "
                           )
    ref_cal_info = tk.Message(ref_cal_labelframe, width=822*r, text=ref_cal_info_string, bg=bgc, fg=fgc, font=labelfont)
    shutter_time_calibration_button = tk.Button(ref_cal_labelframe, text="Verschlusszeit kalibrieren [1]", command=shutter_time_calibration,
                                                bg=bgc, fg=blu, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    reference_window.bind("1", shutter_time_calibration)
    ref_labelframe = tk.LabelFrame(reference_window, text="2.:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ref_info_string = ("Klicken Sie nun auf \"Referenzmessung starten\" oder drücken [2]. Die folgenden Dateien werden im Pfad                                  \n"
                       + Speicherpfad + "/Reference_files erzeugt und können unter \"3.\" betrachtet werden:\n"
                       "\N{Bullet} Das aufgenommene Bild \"reference_Bild.jpg\" \n"
                       "\N{Bullet} Das Bild mit darübergezeichneter Intensitätskurve \"reference_Overlay.jpg\" \n"
                       "\N{Bullet} Das Intensitätsspektrum \"reference_Spektrum.png\" \n"
                       "\N{Bullet} Die Intensitätsdaten in \"reference.csv\". Diese Datei kann auch mit einem Tabellenkalkulationsprogramm geöffnet werden."
                       )
    ref_info = tk.Message(ref_labelframe, width=822*r, text=ref_info_string, bg=bgc, fg=fgc, font=labelfont)    
    reference_button = tk.Button(ref_labelframe, text="Referenzmessung starten [2]", command= reference_main_GUI, font=labelfont, bg=bgc, fg=fgc,
                                 highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    reference_window.bind("2", reference_main_GUI)
    ref_results_labelframe = tk.LabelFrame(reference_window, text="3.: Ergebnisse der neuesten Referenzmessung (Fenster können mit [Esc] wieder geschlossen werden):",
                                           font=labelfont, padx=5, pady=5, bg=bgc, fg=fgc)
    ref_results_pane = tk.PanedWindow(ref_results_labelframe, bg=bgc)
    ref_raw_button = tk.Button(ref_results_pane, text="Bild anzeigen [F5]", command=display_ref_raw, font=labelfont, bg=bgc, fg=fgc, highlightbackground=bgc,
                               activebackground=abc, activeforeground=afc)
    reference_window.bind("<F5>", display_ref_raw)
    ref_results_pane.add(ref_raw_button)
    ref_out_button = tk.Button(ref_results_pane, text="Bild mit Overlay anzeigen [F6]", command=display_ref_out, font=labelfont, bg=bgc, fg=fgc,
                               highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    reference_window.bind("<F6>", display_ref_out)
    ref_results_pane.add(ref_out_button)
    ref_chart_button = tk.Button(ref_results_pane, text="Intensitätsspektrum anzeigen [F7]", command=display_ref_chart, font=labelfont, bg=bgc, fg=fgc,
                                 highlightbackground=bgc, activebackground=abc, activeforeground=afc)
    reference_window.bind("<F7>", display_ref_chart)
    ref_results_pane.add(ref_chart_button)
    ref_csv_button = tk.Button(ref_results_pane, text="Messdaten anzeigen [F8]", command=display_ref_csv, font=labelfont, bg=bgc, fg=fgc, highlightbackground=bgc,
                               activebackground=abc, activeforeground=afc)
    reference_window.bind("<F8>", display_ref_csv)
    ref_results_pane.add(ref_csv_button)
    reference_window_close_button = tk.Button(reference_window, text="Abbrechen [Esc]", bg="red", fg="white", command=reference_close, font=labelfont,
                                              activebackground="red3", activeforeground="white", highlightbackground=bgc)
    reference_window.bind("<Escape>", reference_close)
    
    #Anordnung der Widgets
    ref_cal_labelframe.pack(padx=10*r, pady=10*r)
    ref_cal_info.pack()
    shutter_time_calibration_button.pack()
    ref_labelframe.pack(padx=10*r, pady=10*r)
    ref_info.pack()
    reference_button.pack()
    ref_results_labelframe.pack(padx=10*r, pady=10*r)
    ref_results_pane.pack()
    reference_window_close_button.pack(side="bottom", pady=10*r)
    reference_window.mainloop()
    
    
    
    
# Führe spectrometer.py aus
def main_GUI(event="<F3>"):
    root.withdraw()
    if GIF == True:
        t = threading.Thread(target=open_gif_main, name="Zeige GIF an")
        t.daemon = True
        t.start()
    with open(Settings, "r") as sf:
        st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
    print("st=", st)
    tc2 = st + " "
    with open(Settings, "r") as sf:
        path = sf.readlines()[5].lstrip("save_path = ").rstrip("\n")
    print("path=", path)
    if LED_connected == True:
        with open(Settings, "r") as sf:
            led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
        print("led=", led)
        if led == "100":
            GPIO.output(LED, GPIO.HIGH)
        else:
            t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
            t_led.daemon = True
            t_led.start()
    tc0 = str("python3 " + Speicherpfad + "/Python_scripts/spectrometer.py ")
    tc1 = path + " "
    tc3 = "Standard "
    tc4 = "1"
    terminal_command = tc0 + tc1 + tc2 + tc3 + tc4        
    os.system(terminal_command)
    if LED_connected == True:
        if led is not "100":
            os.system("pkill -9 -f led.py")
        GPIO.output(LED, GPIO.LOW)
    os.system("pkill -9 -f gif_main.py")
    os.system("pkill -9 -f spectrometer.py")
    root.destroy() 
    runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py") 




# Ergebnisse anzeigen
def display_raw(event="<F5>"):
    raw_window = tk.Tk()
    raw_window.config(bg=bgc)
    raww_width = 1300 * r
    raww_height = 1005 * r
    raww_x = (screen_width/2) - (raww_width/2)
    raww_y = (screen_height/2) - (raww_height/2)
    raw_window.geometry("%dx%d+%d+%d" % (raww_width, raww_height, raww_x, raww_y))
    raww_header = tk.Frame(raw_window, bg=hbg)
    raww_icon_image = Image.open(Speicherpfad + "/Images/icon.png") 
    raww_icon_image2 = raww_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    raww_icon_image3 = ImageTk.PhotoImage(raww_icon_image2, master=raw_window) 
    raww_icon_label = tk.Label(raww_header, image=raww_icon_image3, bg=hbg)
    raww_icon_label.image = raww_icon_image3
    raww_icon_image.close()
    raww_header_text = tk.Label(raww_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    raww_header.pack(fill="x")
    raww_icon_label.pack(side="left", padx=5*r)
    raww_header_text.pack(side="right", padx=5*r)
    try:
        raw_image = Image.open(path + "_Bild.jpg")
    except:
        raw_window.withdraw()
        messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
        restart()
    raw_image2 = raw_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
    raw_image3 = ImageTk.PhotoImage(raw_image2, master=raw_window)
    raw_label = tk.Label(raw_window, image=raw_image3, bg=bgc)
    raw_label.pack()
    raw_window.title(path + "_Bild.jpg")
    def esc(event="<Escape>"):
        raw_window.destroy()
    raw_window.bind("<Escape>", esc)
    raw_window.mainloop()
def display_out(event="<F6>"):
    out_window = tk.Tk()
    out_window.config(bg=bgc)
    outw_width = 1300 * r
    outw_height = 1005 * r
    outw_x = (screen_width/2) - (outw_width/2)
    outw_y = (screen_height/2) - (outw_height/2)
    out_window.geometry("%dx%d+%d+%d" % (outw_width, outw_height, outw_x, outw_y))
    outw_header = tk.Frame(out_window, bg=hbg)
    outw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    outw_icon_image2 = outw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    outw_icon_image3 = ImageTk.PhotoImage(outw_icon_image2, master=out_window)
    outw_icon_label = tk.Label(outw_header, image=outw_icon_image3, bg=hbg)
    outw_icon_label.image = outw_icon_image3
    outw_icon_image.close()
    outw_header_text = tk.Label(outw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    outw_header.pack(fill="x")
    outw_icon_label.pack(side="left", padx=5*r)
    outw_header_text.pack(side="right", padx=5*r)
    try:
        out_image = Image.open(path + "_Overlay.jpg")
    except:
        out_window.withdraw()
        messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
        restart()
    out_image2 = out_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
    out_image3 = ImageTk.PhotoImage(out_image2, master=out_window)
    out_label = tk.Label(out_window, image=out_image3, bg=bgc)    
    out_label.pack()
    out_window.title(path + "_Overlay.jpg")
    def esc(event="<Escape>"):
        out_window.destroy()
    out_window.bind("<Escape>", esc)
    out_window.mainloop()
def display_chart(event="<F7>"):
    chart_window = tk.Tk()
    chart_window.config(bg=bgc)
    chartw_width = 1264 * r
    chartw_height = 655 * r
    chartw_x = (screen_width/2) - (chartw_width/2)
    chartw_y = (screen_height/2) - (chartw_height/2)
    chart_window.geometry("%dx%d+%d+%d" % (chartw_width, chartw_height, chartw_x, chartw_y))
    chartw_header = tk.Frame(chart_window, bg=hbg)
    chartw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    chartw_icon_image2 = chartw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    chartw_icon_image3 = ImageTk.PhotoImage(chartw_icon_image2, master=chart_window)
    chartw_icon_label = tk.Label(chartw_header, image=chartw_icon_image3, bg=hbg)
    chartw_icon_label.image = chartw_icon_image3
    chartw_icon_image.close()
    chartw_header_text = tk.Label(chartw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    chartw_header.pack(fill="x")
    chartw_icon_label.pack(side="left", padx=5*r)
    chartw_header_text.pack(side="right", padx=5*r)
    try:
        chart_image = Image.open(path + "_Spektrum.png")
    except:
        chart_window.withdraw()
        messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
        restart()
    chart_image2 = chart_image.resize((int(1260*r), int(620*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
    chart_image3 = ImageTk.PhotoImage(chart_image2, master=chart_window)
    chart_label = tk.Label(chart_window, image=chart_image3, bg=bgc)    
    chart_label.pack()
    chart_window.title(path + "_Spektrum.png")
    def esc(event="<Escape>"):
        chart_window.destroy()
    chart_window.bind("<Escape>", esc)
    chart_window.mainloop()
def display_csv(event="<F8>"):
    csv_window = tk.Toplevel()
    csv_window.config(bg=bgc)
    csv_window.resizable(0, 0)
    csvw_width = 636 * r
    csvw_height = 855 * r
    csvw_x = (screen_width/2) - (csvw_width/2)
    csvw_y = (screen_height/2) - (csvw_height/2)
    csv_window.geometry("%dx%d+%d+%d" % (csvw_width, csvw_height, csvw_x, csvw_y))
    csvw_header = tk.Frame(csv_window, bg=hbg)
    csvw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    csvw_icon_image2 = csvw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    csvw_icon_image3 = ImageTk.PhotoImage(csvw_icon_image2, master=csv_window)
    csvw_icon_label = tk.Label(csvw_header, image=csvw_icon_image3, bg=hbg)
    csvw_icon_label.image = csvw_icon_image3
    csvw_icon_image.close()
    csvw_header_text = tk.Label(csvw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    csvw_header.pack(fill="x")
    csvw_icon_label.pack(side="left", padx=5*r)
    csvw_header_text.pack(side="right", padx=5*r)
    scrollbary = tk.Scrollbar(csv_window, orient="vertical", width=26*r, bg=bgc, highlightbackground=bgc, activebackground=abc, troughcolor=bgc) #default: width=16
    table = ttk.Treeview(csv_window, columns=("w", "i0", "i", "a"), height=int(40*r), selectmode="extended", yscrollcommand=scrollbary.set)
    scrollbary.config(command=table.yview)
    def scroll_down(event="<Down>"):
        new_position0 = scrollbary.get()[0] + 0.01
        new_position1 = scrollbary.get()[1] + 0.01
        scrollbary.set(new_position0, new_position1)
        table.yview_moveto(new_position0)
    def scroll_up(event="<Up>"):
        new_position0 = scrollbary.get()[0] - 0.01
        new_position1 = scrollbary.get()[1] - 0.01
        scrollbary.set(new_position0, new_position1)
        table.yview_moveto(new_position0)
    csv_window.bind("<Down>", scroll_down)
    csv_window.bind("<Up>", scroll_up)
    scrollbary.pack(side="right", fill="y")
    nametofont("TkHeadingFont").configure(size=int(10*r))
    table.heading("w", text="Wellenlänge [nm]", anchor="w")
    table.heading("a", text="Extinktion", anchor="w")
    table.heading("i", text="Intensität", anchor="w")
    table.heading("i0", text="Intensität (Referenzmessung)", anchor="w")
    table.column("#0", stretch="no", minwidth=0, width=0)
    table.column("#1", stretch="no", minwidth=0, width=int(150*r))
    table.column("#2", stretch="no", minwidth=0, width=int(250*r))
    table.column("#3", stretch="no", minwidth=0, width=int(100*r))
    table.column("#4", stretch="no", minwidth=0, width=int(100*r))
    csv_path = path + ".csv"
    with open(Settings, "r") as sf:
        csv_mode = sf.readlines()[10].lstrip("csv_mode = ").rstrip("\n")
    print("csv_mode=", csv_mode)
    try:
        with open(csv_path) as f:
            if csv_mode == "English":
                reader = csv.DictReader(f, delimiter=",")
            else:
                reader = csv.DictReader(f, delimiter=";")
            for row in reader:
                w = row["Wellenlänge [nm]"]
                a = row["Extinktion"]
                i = row["Intensität"]
                i0 = row["Intensität (Referenzmessung)"]
                table.insert("", 0, values=(w, i0, i, a), tags="table_entries")
                table.tag_configure("table_entries", font=labelfont)
    except:
        csv_window.withdraw()
        messagebox.showerror("Fehler", "Entweder existiert die gesuchte Datei nicht oder sie ist falsch formatiert!")
        restart()
    table.pack()
    csv_window.title(csv_path)
    def esc(event="<Escape>"):
        csv_window.destroy()
    csv_window.bind("<Escape>", esc)
    csv_window.mainloop()




# Messreihe
def series(event="<Alt-F3>"):
    root.withdraw()
    series_window = tk.Toplevel()
    series_window.config(bg=bgc)
    serw_width = 864 * r - int(ln(r) * 140)
    serw_height = 818 * r - int(ln(r) * 140)
    serw_x = (screen_width/2) - (serw_width/2)
    serw_y = (screen_height/2) - (serw_height/2)
    series_window.geometry("%dx%d+%d+%d" % (serw_width, serw_height, serw_x, serw_y))
    serw_header = tk.Frame(series_window, bg=hbg)
    serw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
    serw_icon_image2 = serw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
    serw_icon_image3 = ImageTk.PhotoImage(serw_icon_image2, master=series_window)
    serw_icon_label = tk.Label(serw_header, image=serw_icon_image3, bg=hbg)
    serw_icon_label.image = serw_icon_image3
    serw_icon_image.close()
    serw_header_text = tk.Label(serw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
    serw_header.pack(fill="x")
    serw_icon_label.pack(side="left", padx=5*r)
    serw_header_text.pack(side="right", padx=5*r)
    series_window.title("Lambda  |  Messreihe")
    def series_close(event="<Escape>"):
        series_window.destroy()
        root.deiconify()
        
    # Messreihe erweitern
    def series_main_GUI(event="<F3>"):
        series_window.withdraw()
        if GIF == True:
            t = threading.Thread(target=open_gif_main, name="Zeige GIF an")
            t.daemon = True
            t.start()
        with open(Settings, "r") as sf:
            st = sf.readlines()[7].lstrip("shutter_time = ").rstrip("\n")
        print("st=", st)
        tc2 = st + " "
        ser_path_new = path_entry.get()
        with open(Settings, "r") as sf:
            settings = sf.readlines()
        with open(Settings, "w") as sf:
            settings[5] = "save_path = " + ser_path_new + "\n"
            sf.writelines(settings)
        print("ser_path_new=", ser_path_new)
        if LED_connected == True:
            with open(Settings, "r") as sf:
                led = sf.readlines()[6].lstrip("LED_brightness = ").rstrip("\n")
            print("led=", led)
            if led == "100":
                GPIO.output(LED, GPIO.HIGH)
            else:
                t_led = threading.Thread(target=led_on, name="Schalte LED gedimmt an") 
                t_led.daemon = True
                t_led.start()
        tc0 = str("python3 " + Speicherpfad + "/Python_scripts/spectrometer.py ")
        tc1 = ser_path_new + " "
        tc3 = mode_var.get() + " "
        tc4 = series_spinbox.get()
        terminal_command = tc0 + tc1 + tc2 + tc3 + tc4
        os.system(terminal_command)
        if LED_connected == True:
            if led is not "100":
                os.system("pkill -9 -f led.py")
            GPIO.output(LED, GPIO.LOW)
        os.system("pkill -9 -f gif_main.py")
        os.system("pkill -9 -f spectrometer.py")
        series_window.deiconify()
            
    # Ergebnisse der letzten Messung anzeigen
    def display_ser_raw(event="<F5>"):
        ser_raw_window = tk.Tk()
        ser_raw_window.config(bg=bgc)
        ser_raww_width = 1300 * r
        ser_raww_height = 1005 * r
        ser_raww_x = (screen_width/2) - (ser_raww_width/2)
        ser_raww_y = (screen_height/2) - (ser_raww_height/2)
        ser_raw_window.geometry("%dx%d+%d+%d" % (ser_raww_width, ser_raww_height, ser_raww_x, ser_raww_y))
        ser_raww_header = tk.Frame(ser_raw_window, bg=hbg)
        ser_raww_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ser_raww_icon_image2 = ser_raww_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ser_raww_icon_image3 = ImageTk.PhotoImage(ser_raww_icon_image2, master=ser_raw_window)
        ser_raww_icon_label = tk.Label(ser_raww_header, image=ser_raww_icon_image3, bg=hbg)
        ser_raww_icon_label.image = ser_raww_icon_image3
        ser_raww_icon_image.close()
        ser_raww_header_text = tk.Label(ser_raww_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ser_raww_header.pack(fill="x")
        ser_raww_icon_label.pack(side="left", padx=5*r)
        ser_raww_header_text.pack(side="right", padx=5*r)
        ser_path_new = path_entry.get()
        if mode_var.get() == "Erweitert" and int(series_spinbox.get()) > 1:
            ser_path_new = ser_path_new + "_" + series_spinbox.get()
        ser_raw_path = ser_path_new + "_Bild.jpg"
        try:
            ser_raw_image = Image.open(ser_raw_path)
        except:
            ser_raw_window.withdraw()
            messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
            restart()
        ser_raw_image2 = ser_raw_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
        ser_raw_image3 = ImageTk.PhotoImage(ser_raw_image2, master=ser_raw_window)
        ser_raw_label = tk.Label(ser_raw_window, image=ser_raw_image3, bg=bgc)    
        ser_raw_label.pack()
        ser_raw_window.title(ser_raw_path)
        def esc(event="<Escape>"):
            ser_raw_window.destroy()
        ser_raw_window.bind("<Escape>", esc)
        ser_raw_window.mainloop()
    def display_ser_out(event="<F6>"):
        ser_out_window = tk.Tk()
        ser_out_window.config(bg=bgc)
        ser_outw_width = 1300 * r
        ser_outw_height = 1005 * r
        ser_outw_x = (screen_width/2) - (ser_outw_width/2)
        ser_outw_y = (screen_height/2) - (ser_outw_height/2)
        ser_out_window.geometry("%dx%d+%d+%d" % (ser_outw_width, ser_outw_height, ser_outw_x, ser_outw_y))
        ser_outw_header = tk.Frame(ser_out_window, bg=hbg)
        ser_outw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ser_outw_icon_image2 = ser_outw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ser_outw_icon_image3 = ImageTk.PhotoImage(ser_outw_icon_image2, master=ser_out_window)
        ser_outw_icon_label = tk.Label(ser_outw_header, image=ser_outw_icon_image3, bg=hbg)
        ser_outw_icon_label.image = ser_outw_icon_image3
        ser_outw_icon_image.close()
        ser_outw_header_text = tk.Label(ser_outw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ser_outw_header.pack(fill="x")
        ser_outw_icon_label.pack(side="left", padx=5*r)
        ser_outw_header_text.pack(side="right", padx=5*r)
        ser_path_new = path_entry.get()
        if mode_var.get() == "Erweitert" and int(series_spinbox.get()) > 1:
            ser_path_new = ser_path_new + "_" + series_spinbox.get()
        ser_out_path = ser_path_new + "_Overlay.jpg"
        try:
            ser_out_image = Image.open(ser_out_path)
        except:
            ser_out_window.withdraw()
            messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
            restart()
        ser_out_image2 = ser_out_image.resize((int(1296*r), int(972*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
        ser_out_image3 = ImageTk.PhotoImage(ser_out_image2, master=ser_out_window)
        ser_out_label = tk.Label(ser_out_window, image=ser_out_image3, bg=bgc)        
        ser_out_label.pack()
        ser_out_window.title(ser_out_path)
        def esc(event="<Escape>"):
            ser_out_window.destroy()
        ser_out_window.bind("<Escape>", esc)
        ser_out_window.mainloop()
    def display_ser_chart(event="<F7>"):
        ser_chart_window = tk.Tk()
        ser_chart_window.config(bg=bgc)
        ser_chartw_width = 1264 * r
        ser_chartw_height = 655 * r
        ser_chartw_x = (screen_width/2) - (ser_chartw_width/2)
        ser_chartw_y = (screen_height/2) - (ser_chartw_height/2)
        ser_chart_window.geometry("%dx%d+%d+%d" % (ser_chartw_width, ser_chartw_height, ser_chartw_x, ser_chartw_y))
        ser_chartw_header = tk.Frame(ser_chart_window, bg=hbg)
        ser_chartw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ser_chartw_icon_image2 = ser_chartw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ser_chartw_icon_image3 = ImageTk.PhotoImage(ser_chartw_icon_image2, master=ser_chart_window)
        ser_chartw_icon_label = tk.Label(ser_chartw_header, image=ser_chartw_icon_image3, bg=hbg)
        ser_chartw_icon_label.image = ser_chartw_icon_image3
        ser_chartw_icon_image.close()
        ser_chartw_header_text = tk.Label(ser_chartw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ser_chartw_header.pack(fill="x")
        ser_chartw_icon_label.pack(side="left", padx=5*r)
        ser_chartw_header_text.pack(side="right", padx=5*r)
        ser_path_new = path_entry.get()
        if mode_var.get() == "Erweitert" and int(series_spinbox.get()) > 1:
            ser_path_new = ser_path_new + "_" + series_spinbox.get()
        ser_chart_path = ser_path_new + "_Spektrum.png"
        try:
            ser_chart_image = Image.open(ser_chart_path)
        except:
            ser_chart_window.withdraw()
            messagebox.showerror("Fehler", "Die gesuchte Datei scheint nicht zu existieren!")
            restart()
        ser_chart_image2 = ser_chart_image.resize((int(1260*r), int(620*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
        ser_chart_image3 = ImageTk.PhotoImage(ser_chart_image2, master=ser_chart_window)
        ser_chart_label = tk.Label(ser_chart_window, image=ser_chart_image3, bg=bgc)        
        ser_chart_label.pack()
        ser_chart_window.title(ser_chart_path)
        def esc(event="<Escape>"):
            ser_chart_window.destroy()
        ser_chart_window.bind("<Escape>", esc)
        ser_chart_window.mainloop()
    def display_ser_csv(event="<F8>"):
        ser_csv_window = tk.Toplevel()
        ser_csv_window.config(bg=bgc)
        ser_csv_window.resizable(0, 0)
        ser_csvw_width = 844 * r
        ser_csvw_height = 855 * r
        ser_csvw_x = (screen_width/2) - (ser_csvw_width/2)
        ser_csvw_y = (screen_height/2) - (ser_csvw_height/2)
        ser_csv_window.geometry("%dx%d+%d+%d" % (ser_csvw_width, ser_csvw_height, ser_csvw_x, ser_csvw_y))
        ser_csvw_header = tk.Frame(ser_csv_window, bg=hbg)
        ser_csvw_icon_image = Image.open(Speicherpfad + "/Images/icon.png")
        ser_csvw_icon_image2 = ser_csvw_icon_image.resize((int(30*r), int(30*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust
        ser_csvw_icon_image3 = ImageTk.PhotoImage(ser_csvw_icon_image2, master=ser_csv_window)
        ser_csvw_icon_label = tk.Label(ser_csvw_header, image=ser_csvw_icon_image3, bg=hbg)
        ser_csvw_icon_label.image = ser_csvw_icon_image3
        ser_csvw_icon_image.close()
        ser_csvw_header_text = tk.Label(ser_csvw_header, text="Lambda 1.1  |  2021", bg=hbg, fg=hfg, font=labelfont)
        ser_csvw_header.pack(fill="x")
        ser_csvw_icon_label.pack(side="left", padx=5*r)
        ser_csvw_header_text.pack(side="right", padx=5*r)
        scrollbary = tk.Scrollbar(ser_csv_window, orient="vertical", width=26*r, bg=bgc, highlightbackground=bgc, activebackground=abc, troughcolor=bgc) #default: width=16
        scrollbarx = tk.Scrollbar(ser_csv_window, orient="horizontal", width=26*r, bg=bgc, highlightbackground=bgc, activebackground=abc, troughcolor=bgc) #default: width=16
        iteration = int(series_spinbox.get())
        mode = mode_var.get()
        column_string = "w", "i0"
        for x in range(1, iteration + 1, 1):
            column_string = column_string + ("i" + str(x), "a" + str(x))
        table = ttk.Treeview(ser_csv_window, columns=(column_string), height=int(40*r), selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
        scrollbary.config(command=table.yview)
        scrollbary.pack(side="right", fill="y")
        scrollbarx.config(command=table.xview)
        scrollbarx.pack(side="bottom", fill="x")
        def scroll_down(event="<Down>"):
            new_position0 = scrollbary.get()[0] + 0.01
            new_position1 = scrollbary.get()[1] + 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        def scroll_up(event="<Up>"):
            new_position0 = scrollbary.get()[0] - 0.01
            new_position1 = scrollbary.get()[1] - 0.01
            scrollbary.set(new_position0, new_position1)
            table.yview_moveto(new_position0)
        def scroll_right(event="<Right>"):
            new_position0 = scrollbarx.get()[0] + 0.01
            new_position1 = scrollbarx.get()[1] + 0.01
            scrollbarx.set(new_position0, new_position1)
            table.xview_moveto(new_position0)
        def scroll_left(event="<Left>"):
            new_position0 = scrollbarx.get()[0] - 0.01
            new_position1 = scrollbarx.get()[1] - 0.01
            scrollbarx.set(new_position0, new_position1)
            table.xview_moveto(new_position0)
        ser_csv_window.bind("<Down>", scroll_down)
        ser_csv_window.bind("<Up>", scroll_up)
        ser_csv_window.bind("<Right>", scroll_right)
        ser_csv_window.bind("<Left>", scroll_left)
        nametofont("TkHeadingFont").configure(size=int(10*r))
        table.heading("w", text="Wellenlänge [nm]", anchor="w")
        table.heading("i0", text="Intensität (Referenzmessung)", anchor="w")
        for x in range(1, iteration + 1, 1):
            if iteration == 1:
                table.heading("i" + str(x), text="Intensität", anchor="w")
                table.heading("a" + str(x), text="Extinktion", anchor="w")
            else:
                table.heading("i" + str(x), text="Intensität (" + str(x) + ")", anchor="w")
                table.heading("a" + str(x), text="Extinktion (" + str(x) + ")", anchor="w")
        table.column("#0", stretch="no", minwidth=0, width=0)
        table.column("#1", stretch="no", minwidth=0, width=int(150*r))
        table.column("#2", stretch="no", minwidth=0, width=int(250*r))
        for x in range(1, iteration + 1, 1):
            table.column("#" + str(2 * x + 1), stretch="no", minwidth=0, width=int(150*r))
            table.column("#" + str(2 * x + 2), stretch="no", minwidth=0, width=int(150*r))
        ser_path_new = path_entry.get()
        if mode == "Erweitert" and iteration > 1:
            ser_path_new = ser_path_new + "_" + str(iteration)
        ser_csv_path = ser_path_new + ".csv"
        with open(Settings, "r") as sf:
            csv_mode = sf.readlines()[10].lstrip("csv_mode = ").rstrip("\n")
        print("csv_mode=", csv_mode)
        try:
            with open(ser_csv_path) as f:
                if csv_mode == "English":
                    reader = csv.DictReader(f, delimiter=",")
                else:
                    reader = csv.DictReader(f, delimiter=";")
                for row in reader:
                    w = row["Wellenlänge [nm]"]
                    i0 = row["Intensität (Referenzmessung)"]
                    value_tuple = w, i0
                    for x in range(1, iteration + 1, 1):
                        if iteration == 1:
                            value_tuple = value_tuple + (row["Intensität"], row["Extinktion"])
                        else:
                            value_tuple = value_tuple + (row["Intensität (" + str(x) + ")"], row["Extinktion (" + str(x) + ")"])
                    table.insert("", 0, values=(value_tuple), tags="table_entries")
                    table.tag_configure("table_entries", font=labelfont)
        except:
            ser_csv_window.withdraw()
            messagebox.showerror("Fehler", "Entweder existiert die gesuchte Datei nicht oder sie ist falsch formatiert!")
            restart()
        table.pack()
        ser_csv_window.title(ser_csv_path)
        def esc(event="<Escape>"):
            ser_csv_window.destroy()
        ser_csv_window.bind("<Escape>", esc)
        ser_csv_window.mainloop()
                
    # Widgets
    ser_path_labelframe = tk.LabelFrame(series_window, text="1.:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ser_path_info_string1 = (" Die Ergebnisse der Messreihe werden im folgenden Pfad gespeichert:") 
    ser_path_info1 = tk.Label(ser_path_labelframe, width=int(822*r), text=ser_path_info_string1, anchor="w", justify="left", bg=bgc, fg=fgc, font=labelfont)
    ser_path_info2 = tk.Label(ser_path_labelframe, text=path_entry.get(), bg=bgc, fg=blu, font=labelfont)
    ser_path_info_string3 = ("Dabei stellt das Argument hinter dem letzten Schrägstrich den Dateinamen dar. Der Speicherpfad kann im Hauptfenster        \n"
                            "geändert werden, klicken Sie dazu ganz unten auf \"Beenden und zurück zum Hauptfenster\" oder drücken Sie [Esc]."
                            )
    ser_path_info3 = tk.Message(ser_path_labelframe, width=int(822*r), text=ser_path_info_string3, anchor="w", justify="left", bg=bgc, fg=fgc, font=labelfont)
    ser_mode_labelframe = tk.LabelFrame(series_window, text="2.:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ser_mode_info_string = (" Legen Sie fest, in welchem Modus die Messreihe aufgenommen werden soll:                                                                              \n"
                           " \N{Bullet} \"Standard\": Mit jeder neuen Messung werden die folgenden Dateien überschrieben:\n"                       
                           "      \N{Bullet} Das aufgenommene Bild \"_Bild.jpg\" \n" 
                           "      \N{Bullet} Das Bild mit darübergezeichneter Intensitätskurve \"_Overlay.jpg\" \n"
                           "      \N{Bullet} Das Extinktionsspektrum \"_Spektrum.png\" \n"
                           "      \N{Bullet} Die Extinktionsdaten in \".csv\" (Zu dieser werden beim Überschreiben die neuen Daten hinzugefügt).\n"
                           " \N{Bullet} \"Erweitert\": Für jede Messung werden alle Dateien gespeichert."
                           )
    ser_mode_info = tk.Message(ser_mode_labelframe, width=int(822*r), text=ser_mode_info_string, bg=bgc, fg=fgc, font=labelfont)
    radiobutton_frame = tk.Frame(ser_mode_labelframe, bg=bgc)
    mode_var = tk.StringVar(series_window)
    mode_var.set("Standard")
    def select_standard(event="<Alt-s>"):
        mode_var.set("Standard")
    series_window.bind("<Alt-s>", select_standard)
    def select_expanded(event="<Alt-e>"):
        mode_var.set("Erweitert")
    series_window.bind("<Alt-e>", select_expanded)
    mode_radiobutton1 = tk.Radiobutton(radiobutton_frame, text="Standard [Alt + S]", variable=mode_var, value="Standard", bg=bgc, fg=blu, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    mode_radiobutton2 = tk.Radiobutton(radiobutton_frame, text="Erweitert [Alt + E]", variable=mode_var, value="Erweitert", bg=bgc, fg=blu, font=labelfont,
                                       highlightbackground=bgc, activebackground=abc, activeforeground=afc, selectcolor=ebg).pack(side="left")
    ser_labelframe = tk.LabelFrame(series_window, text="3.:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ser_info_string = (" Wählen sie unten aus, die wievielte Messung Sie durchführen wollen.                                                                                          \n"
                       " ACHTUNG: Bei \"1\" wird eine eventuell auf dem Hauptfenster durchgeführte Einzelmessung überschrieben.\n"
                       " Wollen Sie an diese anknüpfen, so beginnen Sie mit \"2\"!\n"
                       " Um die Messung durchzuführen klicken Sie auf \"Messung starten\" oder drücken Sie [F3]."
                       )
    ser_info = tk.Message(ser_labelframe, width=int(822*r), text=ser_info_string, bg=bgc, fg=fgc, font=labelfont)
    series_spinbox_var = tk.StringVar(series_window)
    series_spinbox_var.set("1")
    def series_spinbox_up(event="<Up>"):
        series_spinbox_var.set(str(int(series_spinbox_var.get()) + 1))
    def series_spinbox_down(event="<Down>"):
        if int(series_spinbox_var.get()) > 1:
            series_spinbox_var.set(str(int(series_spinbox_var.get()) - 1))
    series_window.bind("<Up>", series_spinbox_up)
    series_window.bind("<Down>", series_spinbox_down)
    series_spinbox = tk.Spinbox(ser_labelframe, from_=1, to=1000, width=int(5*r), justify="center", font="TkDefaultFont " + str(int(10*r*1.6)), highlightbackground=bgc, activebackground=abc,
                                buttonbackground=bgc, bg=ebg, fg=blu, insertbackground=ebg, selectbackground="green", selectforeground="white", textvariable=series_spinbox_var)    
    series_main_button_image = Image.open(Speicherpfad + "/Images/Messung_starten.png")
    series_main_button_image2 = series_main_button_image.resize((int(536*r), int(100*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
    series_main_button_image3 = ImageTk.PhotoImage(series_main_button_image2, master=series_window)        
    series_main_button = tk.Button(ser_labelframe, image=series_main_button_image3, command=series_main_GUI, bg=bgc, highlightbackground=bgc, activebackground=abc)
    series_window.bind("<F3>", series_main_GUI)
    ser_results_labelframe = tk.LabelFrame(series_window, text="4.: Ergebnisse der neuesten Messung (Fenster können mit [Esc] wieder geschlossen werden):", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
    ser_results_pane = tk.PanedWindow(ser_results_labelframe, bg=bgc)
    ser_raw_button = tk.Button(ser_results_pane, text="Bild anzeigen [F5]", command=display_ser_raw, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    series_window.bind("<F5>", display_ser_raw)
    ser_results_pane.add(ser_raw_button)
    ser_out_button = tk.Button(ser_results_pane, text="Bild mit Overlay anzeigen [F6]", command=display_ser_out, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    series_window.bind("<F6>", display_ser_out)
    ser_results_pane.add(ser_out_button)
    ser_chart_button = tk.Button(ser_results_pane, text="Extinktionsspektrum anzeigen [F7]", command=display_ser_chart, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    series_window.bind("<F7>", display_ser_chart)
    ser_results_pane.add(ser_chart_button)
    ser_csv_button = tk.Button(ser_results_pane, text="Messdaten anzeigen [F8]", command=display_ser_csv, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc, font=labelfont)
    series_window.bind("<F8>", display_ser_csv)
    ser_results_pane.add(ser_csv_button)
    series_window_close_button = tk.Button(series_window, text="Beenden und zurück zum Hauptfenster [Esc]", bg="green", fg="white", command=series_close, font=labelfont, activebackground="dark green", activeforeground="white", highlightbackground=bgc)
    series_window.bind("<Escape>", series_close)
    
    #Anordnung der Widgets
    ser_path_labelframe.pack(padx=10*r, pady=10*r)
    ser_path_info1.pack()
    ser_path_info2.pack(pady=5*r)
    ser_path_info3.pack()
    ser_mode_labelframe.pack(padx=10*r, pady=10*r)
    ser_mode_info.pack()
    radiobutton_frame.pack()
    ser_labelframe.pack(padx=10*r, pady=10*r)
    ser_info.pack()
    series_spinbox.pack(pady=5*r)
    series_main_button.pack()
    ser_results_labelframe.pack(padx=10*r, pady=10*r)
    ser_results_pane.pack()
    series_window_close_button.pack(side="bottom", pady=10*r)
    series_window.mainloop()




# Verhalten der Buttons wenn man mit der Maus darüber schwebt
class HoverButton(tk.Button):
    def __init__(self, master, **kw):
        tk.Button.__init__(self,master=master,**kw)
        self.defaultBackground = self["background"]
        self.defaultForeground = self["foreground"]
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)

    def on_enter(self, e):
        self['background'] = self['activebackground']
        self['foreground'] = self['activeforeground']

    def on_leave(self, e):
        self['background'] = self.defaultBackground
        self['foreground'] = self.defaultForeground





# Widgets
welcome_frame = tk.Frame(root, bg=bgc)
welcome = tk.Message(welcome_frame, width=int(1000*r), text="Willkommen bei Lambda!", anchor="sw", font=labelfont + " bold",
                     bg=bgc, fg=fgc)
settings_button = tk.Button(welcome_frame, text="Einstellungen [F11]", command=open_settings, font=labelfont, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind_all("<F11>", open_settings)
about_button = tk.Button(welcome_frame, text="Über Lambda [F12]", command=about, font=labelfont, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind_all("<F12>", about)
help_button = tk.Button(welcome_frame, text="Hilfe [F1]", command=help_me, font=labelfont, bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind_all("<F1>", help_me)
info_labelframe = tk.LabelFrame(root, text="Hinweise:", padx=5, pady=5, bg=bgc, fg=fgc, font=labelfont)
def info_show(event="<Alt-h>"):
    with open(Settings, "r") as sf:
        settings = sf.readlines()
    with open(Settings, "w") as sf:
        settings[4] = "show_info = " + "True" + "\n"
        sf.writelines(settings)
    print("showinfo= True")
    root.destroy()
    runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")
info_button2 = tk.Button(info_labelframe, text="Hinweise einblenden [Alt + H]", command=info_show, font=labelfont,
                         bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<Alt-h>", info_show)
def info_hide(event="<Control-h>"):
    with open(Settings, "r") as sf:
        settings = sf.readlines()
    with open(Settings, "w") as sf:
        settings[4] = "show_info = " + "False" + "\n"
        sf.writelines(settings)
    print("showinfo= False")
    root.destroy()
    runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py")
info_button1 = tk.Button(info_labelframe, text="Hinweise ausblenden [Strg + H]", command=info_hide, font=labelfont,
                         bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<Control-h>", info_hide)
info_string = ("In den Fenstern kann mit [Tab] und [Leertaste] navigiert werden!\n"
               "1. Falls Sie das angeschlossene Spektrometer zum ersten Mal verwenden, klicken Sie "
               "auf \"Einrichtung des Spektrometers\" oder drücken Sie [Strg + E] und folgen Sie den weiteren Anweisungen. \n"
               "2. OPTIONAL: Die Live-Kamera zeigt ein Livebild aus dem Inneren des Spektrometers. Diese funktioniert am besten, "
               "wenn Sie die externe Lichtquelle erst nach dem Klicken auf \"Live-Kamera starten\" bzw. Drücken von [Strg + K] einschalten. \n"
               "3. Um ein Extinktionsspektrum erstellen zu können ist eine Referenzmessung erforderlich. Klicken Sie dazu auf die "
               "entsprechende Schaltfläche oder drücken Sie [F2] und folgen Sie den weiteren Anweisungen.\n"
               "4. Legen Sie unter \"Speicherpfad\" den Pfad fest, unter dem die Ergebnisse gespeichert werden sollen. "
               "Stellen Sie sicher, dass der angegebene Pfad auch existiert. Das Argument nach dem letzten "
               "Schrägstrich wird zum Dateinamen. \n"
               "5. Nehmen Sie eine Einzelmessung oder Messreihe auf. Es werden im angegebenen Speicherpfad vier Dateien erzeugt: \n"
               "\N{Bullet} Das aufgenommene Bild \"_Bild.jpg\" \n"
               "\N{Bullet} Das Bild mit darübergezeichneter Intensitätskurve \"_Overlay.jpg\" \n"
               "\N{Bullet} Das Extinktionsspektrum \"_Spektrum.png\" \n"
               "\N{Bullet} Die Messdaten in einer .csv-Datei. Diese kann auch mit einem Tabellenkalkulationsprogramm geöffnet werden. \n"
              )
info = tk.Message(info_labelframe, width=int(1000*r), text=info_string, bg=bgc, fg=fgc, font=labelfont)
setup_button = tk.Button(root, text="Einrichtung des Spektrometers [Strg + E]", command=setup, font=labelfont,
                         bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<Control-e>", setup)
camera_button = tk.Button(root, text="Live-Kamera starten [Strg + K]", command=preview_start, font=labelfont,
                          bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<Control-k>", preview_start)
reference_window_button = tk.Button(root, text="Referenzmessung [F2]", command=reference, font=labelfont,
                                    bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<F2>", reference)
with open(Settings, "r") as sf:
    path = sf.readlines()[5].lstrip("save_path = ").rstrip("\n")
print("path=", path)
path_entry_labelframe = tk.LabelFrame(root, text="Speicherpfad:", padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
path_entry_pane = tk.PanedWindow(path_entry_labelframe, bg=bgc)
path_entry = tk.Entry(path_entry_pane, width=int(50*r), font=labelfont, highlightbackground=bgc, bg=ebg, fg=efg, insertbackground=efg, selectbackground="green", selectforeground="white")
path_entry.insert(0, path)
path_entry_pane.add(path_entry)
def open_directory():
    root.filename =  filedialog.asksaveasfilename(initialdir = "/home/pi",title = "Speicherpfad und Name auswählen")
    if root.filename:
        path_entry.delete(0, "end")
        path_entry.insert(0, root.filename)
directory_image = Image.open(Speicherpfad + "/Images/directory.png")
directory_image2 = directory_image.resize((int(25*r), int(25*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
directory_image3 = ImageTk.PhotoImage(directory_image2, master=root)    
directory_button = tk.Button(path_entry_pane, image=directory_image3, bg=bgc, fg=fgc, command=open_directory, font=labelfont, activebackground=abc, activeforeground=fgc, highlightbackground=bgc)
path_entry_pane.add(directory_button)
def reset(event="<Control-s>"):
    path_new = path_entry.get()
    with open(Settings, "r") as sf:
        settings = sf.readlines()
    with open(Settings, "w") as sf:
        settings[5] = "save_path = " + path_new + "\n"
        sf.writelines(settings)
    print("path_new=", path_new)
    root.destroy()
    runpy.run_path(Speicherpfad + "/Python_scripts/GUI.py") 
reset_button = tk.Button(path_entry_labelframe, text="Änderungen speichern [Strg + S]", bg="green", fg="white", command=reset, font=labelfont,
                         activebackground="dark green", activeforeground="white", highlightbackground=bgc)
root.bind("<Control-s>", reset)
main_button_image = Image.open(Speicherpfad + "/Images/Einzelmessung.png")
main_button_image2 = main_button_image.resize((int(536*r), int(100*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
main_button_image3 = ImageTk.PhotoImage(main_button_image2, master=root)
main_button = tk.Button(root, image=main_button_image3, command=main_GUI, bg=bgc, activebackground=abc, highlightbackground=bgc)
root.bind("<F3>", main_GUI)
results_labelframe_string = "Ergebnisse im Pfad " + path + ", sofern diese vorhanden sind (Schließen mit [Esc]):"
results_labelframe = tk.LabelFrame(root, text=results_labelframe_string, padx=5*r, pady=5*r, bg=bgc, fg=fgc, font=labelfont)
results_pane = tk.PanedWindow(results_labelframe, bg=bgc)
raw_button = tk.Button(results_pane, text="Bild anzeigen [F5]", command=display_raw, font=labelfont,
                       bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<F5>", display_raw)
results_pane.add(raw_button)
out_button = tk.Button(results_pane, text="Bild mit Overlay anzeigen [F6]", command=display_out, font=labelfont,
                       bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<F6>", display_out)
results_pane.add(out_button)
chart_button = tk.Button(results_pane, text="Extinktionsspektrum anzeigen [F7]", command=display_chart, font=labelfont,
                         bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<F7>", display_chart)
results_pane.add(chart_button)
csv_button = tk.Button(results_pane, text="Messdaten anzeigen [F8]", command=display_csv, font=labelfont,
                       bg=bgc, fg=fgc, highlightbackground=bgc, activebackground=abc, activeforeground=afc)
root.bind("<F8>", display_csv)
results_pane.add(csv_button)
series_button_image = Image.open(Speicherpfad + "/Images/Messreihe.png")
series_button_image2 = series_button_image.resize((int(536*r), int(100*r)), Image.ANTIALIAS) #Image.ANTIALIAS verhindert Qualitätsverlust     
series_button_image3 = ImageTk.PhotoImage(series_button_image2, master=root)
series_button = tk.Button(root, image=series_button_image3, command=series, bg=bgc, activebackground=abc, highlightbackground=bgc)
root.bind("<Alt-F3>", series)
def close(event="<Alt-F4>"): 
    os.system("pkill -9 -f gif_main.py")
    os.system("pkill -9 -f reference.py")
    os.system("pkill -9 -f setup.py")
    os.system("pkill -9 -f spectrometer.py")
    os.system("pkill -9 -f led.py")
    if LED_connected == True:
        GPIO.output(LED, GPIO.LOW)
    root.destroy()
    sys.exit()
close_button = tk.Button(root, text="Beenden [Alt + F4]", bg="red", fg="white", command=close, font=labelfont,
                         activebackground="red3", activeforeground="white", highlightbackground=bgc)
root.bind_all("<Alt-F4>", close)




# Räumliche Anordnung der Widgets
header.pack(fill="x")
icon_label.pack(side="left", padx=5*r)
header_text.pack(side="right", padx=5*r)
welcome_frame.pack(fill="x")
help_button.pack(side="right")
about_button.pack(side="right")
settings_button.pack(side="right")
welcome.pack(side="left")
info_labelframe.pack(padx=10*r, pady=10*r)
if showinfo == "True":
    info_button1.pack(anchor="w")
    info.pack()
else:
    info_button2.pack(anchor="w")
setup_button.pack()
camera_button.pack(pady=5*r)
reference_window_button.pack()
path_entry_labelframe.pack(padx=10*r, pady=10*r)
path_entry_pane.pack()
reset_button.pack(pady=5*r)
main_button.pack()
results_labelframe.pack(padx=10*r, pady=10*r)
results_pane.pack()
series_button.pack()
close_button.pack(pady=10*r, side="bottom")




# Programm bleibt bis zur manuellen Schließung geöffnet!
root.mainloop()