The Origin Forum
File Exchange
Try Origin for Free
The Origin Forum
Home | Profile | Register | Active Topics | Members | Search | FAQ | Send File to Tech support
 All Forums
 Origin Forum for Programming
 Forum for Python
 problem when integrating many functions into one.

Note: You must be registered in order to post a reply.
To register, click here. Registration is FREE!

Screensize:
UserName:
Password:
Anti-Spam Code:
Format Mode:
Format: BoldItalicizedUnderlineStrikethrough Align LeftCenteredAlign Right Horizontal Rule Insert HyperlinkUpload FileInsert Image Insert CodeInsert QuoteInsert List
   
Message:

* HTML is OFF
* Forum Code is ON
Smilies
Smile [:)] Big Smile [:D] Cool [8D] Blush [:I]
Tongue [:P] Evil [):] Wink [;)] Clown [:o)]
Black Eye [B)] Eight Ball [8] Frown [:(] Shy [8)]
Shocked [:0] Angry [:(!] Dead [xx(] Sleepy [|)]
Kisses [:X] Approve [^] Disapprove [V] Question [?]

 
Check here to subscribe to this topic.
   

T O P I C    R E V I E W
pavi-chem Posted - 08/19/2023 : 06:38:01 AM
OriginPro 2022b (64-bit) SR1
9.9.5.171 (Academic)
Operating System: windows 10
Hi,

I have been working on an FTIR Data Processing application using Python, Tkinter, and the OriginPro library. The application aims to process FTIR data stored in XLSX files, perform various data manipulations, and generate graphs using OriginPro.

The application runs into a problem during the execution of the "Step 2: Reprocess Background" functionality. Specifically, after selecting the input XLSX file and choosing a column to proceed with, the application becomes unresponsive and seems to hang indefinitely.

But the code works fine when I run it without the OriginPro tasks (Step2-bg_process-button.py, Step2-bg_process-loop.py). Only when I integrate them into one code (full-process.py), this error happens and I am unsure why and seems like right after the column is selected, it stops. so, I assume the problem is something with using OriginPro.

I have uploaded the code into a drive with a xlsx file to check. Could you please help me fix this error?
I also tried to run as administrator and still same issue. i am confused at this point. any advice would be great.

https://drive.google.com/drive/folders/1iTsgu27A215BDKowbooem94HnQgGe1pY?usp=sharing

import os
import tkinter as tk
from tkinter import ttk, filedialog, simpledialog, messagebox
import originpro as op
import pandas as pd
import sys


# Code snippet 1: Rename columns
def rename_columns():
    def rename_columns_action():
        # Select the CSV file
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])

        if file_path:
            try:
                # Prompt for start and end voltage values
                start_voltage = float(simpledialog.askstring("Start Voltage", "Enter the starting voltage:"))
                mid_voltage = float(simpledialog.askstring("Mid Voltage", "Enter the ending voltage:"))

                # Read the CSV file
                df = pd.read_csv(file_path)

                # Get the headers
                headers = df.columns.tolist()

                # Calculate the voltage step
                step_up = (mid_voltage - start_voltage) / (len(headers) // 2 - 1)
                step_down = (start_voltage - mid_voltage) / (len(headers) // 2 - 1)

                # Rename the columns
                for i in range(1, len(headers)):
                    if i <= len(headers) // 2:
                        voltage = start_voltage + (i - 1) * step_up
                    else:
                        voltage = mid_voltage + (i - len(headers) // 2 - 1) * step_down
                    new_header = "{:.2f}".format(voltage)  # Format the voltage with 2 decimal places
                    df.rename(columns={headers[i]: new_header}, inplace=True)

                # Save the renamed data to XLSX file
                save_path = os.path.splitext(file_path)[0] + "_renamed.xlsx"
                df.to_excel(save_path, index=False)

                # Open the folder where the output files are saved
                os.startfile(save_path)

                messagebox.showinfo("Success", "Columns renamed successfully. Saved as " + save_path)
            except Exception as e:
                messagebox.showerror("Error", "An error occurred: " + str(e))

    rename_columns_action()


root = tk.Tk()
root.withdraw()


# End of Code snippet 1: Rename columns

# code 2 start
def bg_processing():
    # Select the CSV file
    xlsx_file_path = filedialog.askopenfilename(title="Select Input XLSX File", filetypes=[("XLSX Files", "*.xlsx")])

    if xlsx_file_path:
        try:
            # Read the input XLSX file and rename the sheets
            xlsx = pd.ExcelFile(xlsx_file_path)
            sheets = xlsx.sheet_names
            df = None  # Initialize df variable
            wavenumber_column = None  # Initialize wavenumber_column variable

            for i, sheet in enumerate(sheets):
                df_sheet = pd.read_excel(xlsx_file_path, sheet_name=sheet)
                df_sheet.to_excel(xlsx_file_path, sheet_name=f"Sheet{i + 1}", index=False)

                if i == 0:
                    df = df_sheet
                    wavenumber_column = df_sheet["Wavenumber"]

            # Create a Tkinter window for column selection
            column_window = tk.Tk()
            column_window.title("Select Column")
            column_window.geometry("300x100")

            # Create a label for column selection
            column_label = ttk.Label(column_window, text="Choose a column:")
            column_label.pack()

            # Create a combobox for column selection
            column_combobox = ttk.Combobox(column_window, values=df.columns.tolist())
            column_combobox.pack()

            # Create a button to confirm column selection
            confirm_button = ttk.Button(column_window, text="Confirm", command=column_window.quit)
            confirm_button.pack()

            # Run the column selection window
            column_window.mainloop()
            # Get the chosen column
            chosen_column = column_combobox.get()

            # Create a new sheet for processing
            processed_sheet = pd.DataFrame()
            processed_sheet["Wavenumber"] = wavenumber_column

            for column in df.columns[1:]:
                if column == chosen_column:
                    processed_sheet[column] = 0
                else:
                    processed_sheet[column] = df[column] - df[chosen_column]

            # Prompt for the output directory
            xlsx_output_dir = filedialog.askdirectory(title="Select Output Directory")

            # Get the input filename without extension
            input_xlsx_file_name = os.path.splitext(os.path.basename(xlsx_file_path))[0]

            # Construct the output file path
            output_xlsx_file_name = f"{input_xlsx_file_name}_{chosen_column}.xlsx"
            output_xlsx_file_path = os.path.join(xlsx_output_dir, output_xlsx_file_name)

            # Save the processed sheet to a new workbook
            with pd.ExcelWriter(output_xlsx_file_path, engine="openpyxl") as writer:
                processed_sheet.to_excel(writer, sheet_name="Sheet1", index=False)

            # Open the folder where the output files are saved
            os.startfile(xlsx_output_dir)

            # Show completion message
            message = f"Processing completed! Output saved as:\n{output_xlsx_file_path}"
            messagebox.showinfo("Processing Complete", message)
            column_window.destroy()
        except Exception as e:
            messagebox.showerror("Error", "An error occurred: " + str(e))


root = tk.Tk()
root.withdraw()


# code 2 end

# Code snippet 3: Create Origin graphs
def create_origin_graphs():
    def origin_shutdown_exception_hook(exctype, value, traceback):
        """Ensures Origin gets shut down if an uncaught exception"""
        op.exit()
        sys.__excepthook__(exctype, value, traceback)

    sys.excepthook = origin_shutdown_exception_hook

    # Only run if external Python
    if op.oext:
        # Create a new Origin project
        op.new()
        op.set_show(True)

    try:
        # Prompt user to select an Origin template file for graph 1
        template_file_path_1 = filedialog.askopenfilename(title="Select Origin Template File for Graph 1",
                                                          filetypes=[("Origin Template Files", "*.otpu")])

        # Prompt user to select a data file (CSV or XLSX) for the selected template
        data_file_types = [("CSV Files", "*.csv"), ("XLSX Files", "*.xlsx")]
        csv_file_path_1 = filedialog.askopenfilename(
            title=f"Select Data File for {os.path.basename(template_file_path_1)}",
            filetypes=data_file_types)

        # Load the CSV file into Origin worksheet
        wks = op.new_sheet()
        wks.from_file(csv_file_path_1, False)

        # Create a new graph using the selected template for graph 1
        gr1 = op.new_graph(template=template_file_path_1)
        gr1[0].add_plot(wks, 1, 0)
        gr1[0].rescale()

        # Add more graphs
        more_graphs = True
        graph_num = 2

        while more_graphs:
            # Prompt user to select an Origin template file for the graph
            template_file_path = filedialog.askopenfilename(title=f"Select Origin Template File for Graph {graph_num}",
                                                            filetypes=[("Origin Template Files", "*.otpu")])

            # Prompt user to select an XLSX file for the graph
            xlsx_file_path = filedialog.askopenfilename(
                title=f"Select XLSX File for {os.path.basename(template_file_path)}",
                filetypes=[("XLSX Files", "*.xlsx")])

            # Load the XLSX file into a new worksheet
            wks = op.new_sheet()
            wks.from_file(xlsx_file_path, False)

            # Create a graph page with the user-selected template for the graph
            gr = op.new_graph(template=template_file_path)
            gl = gr[0]

            # Prompt user for the range of columns to plot for the graph
            column_range = simpledialog.askstring("Range of Columns",
                                                  f"Enter the range of columns (e.g., 1-12) for Graph {graph_num}:")

            start_col, end_col = map(int, column_range.split("-"))
            y_columns = list(range(start_col, end_col + 1))

            for col in y_columns:
                plot = gl.add_plot(wks, col, 0)

            # Group and Rescale the graph
            gl.group()
            gl.rescale()

            # Prompt user if they want to add more graphs
            response = tk.messagebox.askyesno("Add More Graphs", "Do you want to add more graphs?")

            if response:
                graph_num += 1
            else:
                more_graphs = False

        # Tile all windows
        op.lt_exec('win-s T')

        # Prompt user for the output Origin file name
        output_file_path = filedialog.asksaveasfilename(title="Save Output Origin File",
                                                        filetypes=[("Origin Project Files", "*.opju")])

        # Creating a notes window
        nt = op.new_notes()

        # Appending input information to the notes
        nt.append("Input Information:")
        nt.append(f"Graph 1 Template: {os.path.basename(template_file_path_1)}")
        nt.append(f"Graph 1 CSV File: {os.path.basename(csv_file_path_1)}")

        for i in range(2, graph_num + 1):
            template_var = locals().get(f"template_file_path_{i}")
            csv_var = locals().get(f"csv_file_path_{i}")

            if template_var and csv_var:
                nt.append(f"\nGraph {i} Template: {os.path.basename(template_var)}")
                nt.append(f"Graph {i} CSV File: {os.path.basename(csv_var)}")

        # Appending folder path information to the notes
        nt.append("\nFolder Paths:")
        nt.append(f"Graph 1 Folder: {os.path.dirname(template_file_path_1)}")

        for i in range(2, graph_num + 1):
            template_var = locals().get(f"template_file_path_{i}")

            if template_var:
                nt.append(f"Graph {i} Folder: {os.path.dirname(template_var)}")

        nt.append(f"Output Folder: {os.path.dirname(output_file_path)}")

        # Appending output file information to the notes
        nt.append("\nOutput Information:")
        nt.append(f"Output File: {os.path.basename(output_file_path)}")

        # Displaying the note
        nt.view = 1

        # Tile all windows
        op.lt_exec('win-s T')

        # Save the project to the specified output file path
        if op.oext:
            output_file_path = os.path.abspath(output_file_path)
            op.save(output_file_path)

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        op.exit()


# End of Code snippet 3: Create Origin graphs


# Code snippet 4: Add graphs to existing Origin project
def add_graphs_to_project():
    def origin_shutdown_exception_hook(exctype, value, traceback):
        """Ensures Origin gets shut down if an uncaught exception"""
        op.exit()
        sys.__excepthook__(exctype, value, traceback)

    sys.excepthook = origin_shutdown_exception_hook

    # Only run if external Python
    if op.oext:
        op.set_show(True)

    def save_origin_project(output_path):
        try:
            op.save(output_path)
            return True  # Save operation successful
        except PermissionError:
            return False  # Save operation failed due to read-only
        except Exception as e:
            print(f"An error occurred while saving: {str(e)}")
            return False  # Save operation failed for other reasons

    def add_graphs_to_project_action():
        try:
            # Prompt user to select an existing Origin project file
            origin_file_path = filedialog.askopenfilename(title="Select Existing Origin Project File",
                                                          filetypes=[("Origin Project Files", "*.opju")])

            # Load the existing Origin project file
            op.open(origin_file_path)

            # Add more graphs
            more_graphs = True
            graph_num = 1

            while more_graphs:
                # Prompt user to select an Origin template file for the graph
                template_file_path = filedialog.askopenfilename(
                    title=f"Select Origin Template File for Graph {graph_num}",
                    filetypes=[("Origin Template Files", "*.otpu")])

                # Prompt user to select an XLSX file for the graph
                data_file_types = [("CSV Files", "*.csv"), ("XLSX Files", "*.xlsx")]
                xlsx_file_path = filedialog.askopenfilename(
                    title=f"Select XLSX File for {os.path.basename(template_file_path)}",
                    filetypes=data_file_types)

                # Load the XLSX file into a new worksheet
                wks = op.new_sheet()
                wks.from_file(xlsx_file_path, False)

                # Create a graph page with the user-selected template for the graph
                gr = op.new_graph(template=template_file_path)
                gl = gr[0]

                # Prompt user for the range of columns to plot for the graph
                column_range = simpledialog.askstring("Range of Columns",
                                                      f"Enter the range of columns (e.g., 1-12) for Graph {graph_num}:")

                start_col, end_col = map(int, column_range.split("-"))
                y_columns = list(range(start_col, end_col + 1))

                for col in y_columns:
                    gl.add_plot(wks, col, 0)

                # Group and Rescale the graph
                gl.group()
                gl.rescale()

                # Prompt user if they want to add more graphs
                response = tk.messagebox.askyesno("Add More Graphs", "Do you want to add more graphs?")

                if response:
                    graph_num += 1
                else:
                    more_graphs = False

            # Tile all windows
            op.lt_exec('win-s T')

            # Prompt user for the output Origin project file name and location
            output_file_path = filedialog.asksaveasfilename(title="Save Output Origin File As",
                                                            filetypes=[("Origin Project Files", "*.opju")])

            if not output_file_path:
                print("Save operation canceled by user.")
                op.exit()
                return  # Exit the function if the user cancels the save operation

            # Try to save the project file
            output_file_path = os.path.abspath(output_file_path)
            success = save_origin_project(output_file_path)

            # If the save operation failed due to read-only, prompt user for a new file path
            while not success:
                new_output_path = filedialog.asksaveasfilename(title="Save Output Origin File As",
                                                               filetypes=[("Origin Project Files", "*.opju")])
                if not new_output_path:
                    print("Save operation canceled by user.")
                    op.exit()
                    break  # Exit the loop if the user cancels the save operation

                new_output_path = os.path.abspath(new_output_path)
                success = save_origin_project(new_output_path)

                if success:
                    message = f"Processing completed! Output saved as:\n{new_output_path}"
                    messagebox.showinfo("Processing Complete", message)
                    op.exit()
                    break  # Exit the loop if the new save is successful
                else:
                    # Display an error message if the new save location is also read-only
                    messagebox.showerror("Error",
                                         "Selected save location is read-only. Please choose a different location.")
                    continue  # Continue the loop and prompt the user again

        except Exception as e:
            print(f"An error occurred: {str(e)}")
            op.exit()

    add_graphs_to_project_action()


root = tk.Tk()
root.withdraw()


# End of Code snippet 4: Add graphs to existing Origin project


# Code snippet 5: Function to exit the application
def exit_application():
    try:
        # Close the active Origin project
        op.exit()
        window.destroy()  # Close the main GUI window, which ends the tkinter event loop
    except Exception as e:
        print(f"An error occurred while closing Origin: {str(e)}")


# End of Code snippet 5: Function to exit the application


# Create the main GUI window
window = tk.Tk()
window.title("FTIR Data Processing")
window.geometry("300x230")

# Create a frame to contain the buttons and align it to the left
button_frame = tk.Frame(window, padx=20, pady=20)
button_frame.pack(anchor="w")  # Use "w" to anchor (justify) the frame to the left

# Create buttons with some styling
button_style = {
    "font": ("Helvetica", 14),
    "width": 30,
    "height": 2,
    "bd": 2,  # Border thickness
    "relief": "solid",  # Border style
}

# Create buttons for each functionality
rename_columns_button = tk.Button(window, text="Step 1: Rename Columns", command=rename_columns, bg="light blue")
process_background_data_button = tk.Button(window, text="Step 2: Reprocess Background", command=bg_processing,
                                           bg="light blue")
create_origin_graphs_button = tk.Button(window, text="Step 3: Create Origin Project to add Graphs",
                                        command=create_origin_graphs, bg="light blue")
add_to_project_button = tk.Button(window, text="Step 4: Add Graphs to Existing Origin Project",
                                  command=add_graphs_to_project, bg="light blue")
exit_button = tk.Button(window, text="Exit Application", command=exit_application, bg="red")

# Pack the buttons with some spacing and justify to the left
rename_columns_button.pack(pady=10, anchor="w")
process_background_data_button.pack(pady=10, anchor="w")
create_origin_graphs_button.pack(pady=10, anchor="w")
add_to_project_button.pack(pady=10, anchor="w")
exit_button.pack(pady=10, anchor="w", )

# Start the tkinter event loop
window.mainloop()








Thanks a bunch!
Pavi.
7   L A T E S T    R E P L I E S    (Newest First)
JacquelineHe Posted - 12/15/2023 : 06:18:42 AM
Hi Pavi,

Origin 2024 is available!

Some new features are supported, or issues are fixed.

The issue "Certain py tkinter script hangs when originpro is imported" (ORG-27617) has been fixed in this version.

Please download Origin 2024 from the link below, install and try it.
http://www.originlab.com/demodownload.aspx

We are looking for your feedback! Any suggestion will be appreciated!

Thanks
Jacqueline He
OriginLab
minimax Posted - 08/24/2023 : 9:49:53 PM
Hi Pavi,

Good to know the update works.

But in your new script, op.exit() is removed before window.quit() line, which seem not proper?

If I directly click "Exit Application" button, it will fail.
pavi-chem Posted - 08/24/2023 : 05:50:47 AM
Hi minimax,

it works after the upgrade. Amazing! :)

here is the whole code just in case:

import os
import tkinter as tk
from tkinter import ttk, filedialog, simpledialog, messagebox
import originpro as op
import pandas as pd
import sys


# Code snippet 1: Rename columns
def rename_columns():
    def rename_columns_action():
        # Select the CSV file
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])

        if file_path:
            try:
                # Prompt for start and end voltage values
                start_voltage = float(simpledialog.askstring("Start Voltage", "Enter the starting voltage:"))
                mid_voltage = float(simpledialog.askstring("Mid Voltage", "Enter the ending voltage:"))

                # Read the CSV file
                df = pd.read_csv(file_path)

                # Get the headers
                headers = df.columns.tolist()

                # Calculate the voltage step
                step_up = (mid_voltage - start_voltage) / (len(headers) // 2 - 1)
                step_down = (start_voltage - mid_voltage) / (len(headers) // 2 - 1)

                # Rename the columns
                for i in range(1, len(headers)):
                    if i <= len(headers) // 2:
                        voltage = start_voltage + (i - 1) * step_up
                    else:
                        voltage = mid_voltage + (i - len(headers) // 2 - 1) * step_down
                    new_header = "{:.2f}".format(voltage)  # Format the voltage with 2 decimal places
                    df.rename(columns={headers[i]: new_header}, inplace=True)

                # Save the renamed data to XLSX file
                save_path = os.path.splitext(file_path)[0] + "_renamed.xlsx"
                df.to_excel(save_path, index=False)

                # Open the folder where the output files are saved
                os.startfile(save_path)

                messagebox.showinfo("Success", "Columns renamed successfully. Saved as " + save_path)
            except Exception as e:
                messagebox.showerror("Error", "An error occurred: " + str(e))

    rename_columns_action()


root = tk.Tk()
root.withdraw()


# End of Code snippet 1: Rename columns

# code 2 start
def bg_processing():
    # Select the CSV file
    xlsx_file_path = filedialog.askopenfilename(title="Select Input XLSX File", filetypes=[("XLSX Files", "*.xlsx")])

    if xlsx_file_path:
        try:
            # Read the input XLSX file and rename the sheets
            xlsx = pd.ExcelFile(xlsx_file_path)
            sheets = xlsx.sheet_names
            df = None  # Initialize df variable
            wavenumber_column = None  # Initialize wavenumber_column variable

            for i, sheet in enumerate(sheets):
                df_sheet = pd.read_excel(xlsx_file_path, sheet_name=sheet)
                df_sheet.to_excel(xlsx_file_path, sheet_name=f"Sheet{i + 1}", index=False)

                if i == 0:
                    df = df_sheet
                    wavenumber_column = df_sheet["Wavenumber"]

            # Create a Tkinter window for column selection
            column_window = tk.Tk()
            column_window.title("Select Column")
            column_window.geometry("300x100")

            # Create a label for column selection
            column_label = ttk.Label(column_window, text="Choose a column:")
            column_label.pack()

            # Create a combobox for column selection
            column_combobox = ttk.Combobox(column_window, values=df.columns.tolist())
            column_combobox.pack()

            # Create a button to confirm column selection
            confirm_button = ttk.Button(column_window, text="Confirm", command=column_window.quit)
            confirm_button.pack()

            # Run the column selection window
            column_window.mainloop()
            # Get the chosen column
            chosen_column = column_combobox.get()

            # Create a new sheet for processing
            processed_sheet = pd.DataFrame()
            processed_sheet["Wavenumber"] = wavenumber_column

            for column in df.columns[1:]:
                if column == chosen_column:
                    processed_sheet[column] = 0
                else:
                    processed_sheet[column] = df[column] - df[chosen_column]

            # Prompt for the output directory
            xlsx_output_dir = filedialog.askdirectory(title="Select Output Directory")

            # Get the input filename without extension
            input_xlsx_file_name = os.path.splitext(os.path.basename(xlsx_file_path))[0]

            # Construct the output file path
            output_xlsx_file_name = f"{input_xlsx_file_name}_{chosen_column}.xlsx"
            output_xlsx_file_path = os.path.join(xlsx_output_dir, output_xlsx_file_name)

            # Save the processed sheet to a new workbook
            with pd.ExcelWriter(output_xlsx_file_path, engine="openpyxl") as writer:
                processed_sheet.to_excel(writer, sheet_name="Sheet1", index=False)

            # Open the folder where the output files are saved
            os.startfile(xlsx_output_dir)

            # Show completion message
            message = f"Processing completed! Output saved as:\n{output_xlsx_file_path}"
            messagebox.showinfo("Processing Complete", message)
            column_window.destroy()
        except Exception as e:
            messagebox.showerror("Error", "An error occurred: " + str(e))


root = tk.Tk()
root.withdraw()


# Code snippet 2 end

# Code snippet 3: Create Origin graphs
def create_origin_graphs():
    def origin_shutdown_exception_hook(exctype, value, traceback):
        """Ensures Origin gets shut down if an uncaught exception"""
        op.exit()
        sys.__excepthook__(exctype, value, traceback)

    sys.excepthook = origin_shutdown_exception_hook

    # Only run if external Python
    if op.oext:
        # Create a new Origin project
        op.new()
        op.set_show(True)

    try:
        # Prompt user to select an Origin template file for graph 1
        template_file_path_1 = filedialog.askopenfilename(title="Select Origin Template File for Graph 1",
                                                          filetypes=[("Origin Template Files", "*.otpu")])

        # Prompt user to select a data file (CSV or XLSX) for the selected template
        data_file_types = [("CSV Files", "*.csv"), ("XLSX Files", "*.xlsx")]
        csv_file_path_1 = filedialog.askopenfilename(
            title=f"Select Data File for {os.path.basename(template_file_path_1)}",
            filetypes=data_file_types)

        # Load the CSV file into Origin worksheet
        wks = op.new_sheet()
        wks.from_file(csv_file_path_1, False)

        # Create a new graph using the selected template for graph 1
        gr1 = op.new_graph(template=template_file_path_1)
        gr1[0].add_plot(wks, 1, 0)
        gr1[0].rescale()

        # Add more graphs
        more_graphs = True
        graph_num = 2

        while more_graphs:
            # Prompt user to select an Origin template file for the graph
            template_file_path = filedialog.askopenfilename(title=f"Select Origin Template File for Graph {graph_num}",
                                                            filetypes=[("Origin Template Files", "*.otpu")])

            # Prompt user to select an XLSX file for the graph
            xlsx_file_path = filedialog.askopenfilename(
                title=f"Select XLSX File for {os.path.basename(template_file_path)}",
                filetypes=[("XLSX Files", "*.xlsx")])

            # Load the XLSX file into a new worksheet
            wks = op.new_sheet()
            wks.from_file(xlsx_file_path, False)

            # Create a graph page with the user-selected template for the graph
            gr = op.new_graph(template=template_file_path)
            gl = gr[0]

            # Prompt user for the range of columns to plot for the graph
            column_range = simpledialog.askstring("Range of Columns",
                                                  f"Enter the range of columns (e.g., 1-12) for Graph {graph_num}:")

            start_col, end_col = map(int, column_range.split("-"))
            y_columns = list(range(start_col, end_col + 1))

            for col in y_columns:
                plot = gl.add_plot(wks, col, 0)

            # Group and Rescale the graph
            gl.group()
            gl.rescale()

            # Prompt user if they want to add more graphs
            response = tk.messagebox.askyesno("Add More Graphs", "Do you want to add more graphs?")

            if response:
                graph_num += 1
            else:
                more_graphs = False

        # Tile all windows
        op.lt_exec('win-s T')

        # Prompt user for the output Origin file name
        output_file_path = filedialog.asksaveasfilename(title="Save Output Origin File",
                                                        filetypes=[("Origin Project Files", "*.opju")])

        # Creating a notes window
        nt = op.new_notes()

        # Appending input information to the notes
        nt.append("Input Information:")
        nt.append(f"Graph 1 Template: {os.path.basename(template_file_path_1)}")
        nt.append(f"Graph 1 CSV File: {os.path.basename(csv_file_path_1)}")

        for i in range(2, graph_num + 1):
            template_var = locals().get(f"template_file_path_{i}")
            csv_var = locals().get(f"csv_file_path_{i}")

            if template_var and csv_var:
                nt.append(f"\nGraph {i} Template: {os.path.basename(template_var)}")
                nt.append(f"Graph {i} CSV File: {os.path.basename(csv_var)}")

        # Appending folder path information to the notes
        nt.append("\nFolder Paths:")
        nt.append(f"Graph 1 Folder: {os.path.dirname(template_file_path_1)}")

        for i in range(2, graph_num + 1):
            template_var = locals().get(f"template_file_path_{i}")

            if template_var:
                nt.append(f"Graph {i} Folder: {os.path.dirname(template_var)}")

        nt.append(f"Output Folder: {os.path.dirname(output_file_path)}")

        # Appending output file information to the notes
        nt.append("\nOutput Information:")
        nt.append(f"Output File: {os.path.basename(output_file_path)}")

        # Displaying the note
        nt.view = 1

        # Tile all windows
        op.lt_exec('win-s T')

        # Save the project to the specified output file path
        if op.oext:
            output_file_path = os.path.abspath(output_file_path)
            op.save(output_file_path)

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        op.exit()


# End of Code snippet 3: Create Origin graphs


# Code snippet 4: Add graphs to existing Origin project
def add_graphs_to_project():
    def origin_shutdown_exception_hook(exctype, value, traceback):
        """Ensures Origin gets shut down if an uncaught exception"""
        op.exit()
        sys.__excepthook__(exctype, value, traceback)

    sys.excepthook = origin_shutdown_exception_hook

    # Only run if external Python
    if op.oext:
        op.set_show(True)

    def save_origin_project(output_path):
        try:
            op.save(output_path)
            return True  # Save operation successful
        except PermissionError:
            return False  # Save operation failed due to read-only
        except Exception as e:
            print(f"An error occurred while saving: {str(e)}")
            return False  # Save operation failed for other reasons

    def add_graphs_to_project_action():
        try:
            # Prompt user to select an existing Origin project file
            origin_file_path = filedialog.askopenfilename(title="Select Existing Origin Project File",
                                                          filetypes=[("Origin Project Files", "*.opju")])

            # Load the existing Origin project file
            op.open(origin_file_path)

            # Add more graphs
            more_graphs = True
            graph_num = 1

            while more_graphs:
                # Prompt user to select an Origin template file for the graph
                template_file_path = filedialog.askopenfilename(
                    title=f"Select Origin Template File for Graph {graph_num}",
                    filetypes=[("Origin Template Files", "*.otpu")])

                # Prompt user to select an XLSX file for the graph
                data_file_types = [("CSV Files", "*.csv"), ("XLSX Files", "*.xlsx")]
                xlsx_file_path = filedialog.askopenfilename(
                    title=f"Select XLSX File for {os.path.basename(template_file_path)}",
                    filetypes=data_file_types)

                # Load the XLSX file into a new worksheet
                wks = op.new_sheet()
                wks.from_file(xlsx_file_path, False)

                # Create a graph page with the user-selected template for the graph
                gr = op.new_graph(template=template_file_path)
                gl = gr[0]

                # Prompt user for the range of columns to plot for the graph
                column_range = simpledialog.askstring("Range of Columns",
                                                      f"Enter the range of columns (e.g., 1-12) for Graph {graph_num}:")

                start_col, end_col = map(int, column_range.split("-"))
                y_columns = list(range(start_col, end_col + 1))

                for col in y_columns:
                    gl.add_plot(wks, col, 0)

                # Group and Rescale the graph
                gl.group()
                gl.rescale()

                # Prompt user if they want to add more graphs
                response = tk.messagebox.askyesno("Add More Graphs", "Do you want to add more graphs?")

                if response:
                    graph_num += 1
                else:
                    more_graphs = False

            # Tile all windows
            op.lt_exec('win-s T')

            # Prompt user for the output Origin project file name and location
            output_file_path = filedialog.asksaveasfilename(title="Save Output Origin File As",
                                                            filetypes=[("Origin Project Files", "*.opju")])

            if not output_file_path:
                print("Save operation canceled by user.")
                op.exit()
                return  # Exit the function if the user cancels the save operation

            # Try to save the project file
            output_file_path = os.path.abspath(output_file_path)
            success = save_origin_project(output_file_path)

            # If the save operation failed due to read-only, prompt user for a new file path
            while not success:
                new_output_path = filedialog.asksaveasfilename(title="Save Output Origin File As",
                                                               filetypes=[("Origin Project Files", "*.opju")])
                if not new_output_path:
                    print("Save operation canceled by user.")
                    op.exit()
                    break  # Exit the loop if the user cancels the save operation

                new_output_path = os.path.abspath(new_output_path)
                success = save_origin_project(new_output_path)

                if success:
                    message = f"Processing completed! Output saved as:\n{new_output_path}"
                    messagebox.showinfo("Processing Complete", message)
                    op.exit()
                    break  # Exit the loop if the new save is successful
                else:
                    # Display an error message if the new save location is also read-only
                    messagebox.showerror("Error",
                                         "Selected save location is read-only. Please choose a different location.")
                    continue  # Continue the loop and prompt the user again

        except Exception as e:
            print(f"An error occurred: {str(e)}")
            op.exit()

    add_graphs_to_project_action()


root = tk.Tk()
root.withdraw()


# End of Code snippet 4: Add graphs to existing Origin project

# Code snippet 5: Function to exit the application
def exit_application():
    try:
        window.quit()  # Close the main GUI window, which ends the tkinter event loop
    except Exception as e:
        print(f"An error occurred while closing Origin: {str(e)}")


# End of Code snippet 5: Function to exit the application

# Create the main GUI window
window = tk.Tk()
window.title("FTIR Data Processing")
window.geometry("400x400")

# Create a frame for the header
header_frame = tk.Frame(window, padx=20, pady=20)
header_frame.pack()

# Create a label for the header
header_label = tk.Label(header_frame, text="FTIR Data Processing", font=("Helvetica", 16, "bold"))
header_label.pack()

# Create a frame for the content
content_frame = tk.Frame(window, padx=20, pady=20)
content_frame.pack()

# Step 1 Section
label_step1 = tk.Label(content_frame, text="Step 1: Rename the header with a CV voltage range.")
label_step1.pack(anchor="w")

rename_columns_button = tk.Button(content_frame, text="Rename Columns", command=rename_columns, bg="light blue")
rename_columns_button.pack(pady=5, anchor="w")

# Step 2 Section
label_step2 = tk.Label(content_frame, text="Step 2: Change the background spectrum with a chosen column.")
label_step2.pack(anchor="w")

process_background_data_button = tk.Button(content_frame, text="Reprocess Background", command=bg_processing,
                                           bg="light blue")
process_background_data_button.pack(pady=5, anchor="w")

# Create labels for step instructions
step3_label = tk.Label(content_frame, text="Step 3: Create Origin Project to add Graphs")
step3_label.pack(anchor="w")  # Align label to the left

# Create a button for Step 3 functionality
create_origin_graphs_button = tk.Button(content_frame, text="Create Origin Project",
                                        command=create_origin_graphs, bg="light blue")
create_origin_graphs_button.pack(pady=5, anchor="w")

# Create a label for Step 4
step4_label = tk.Label(content_frame, text="Step 4: Add Graphs to Existing Origin Project")
step4_label.pack(anchor="w")

# Create a button for Step 4 functionality
add_to_project_button = tk.Button(content_frame, text="Existing Origin Project",
                                  command=add_graphs_to_project, bg="light blue")
add_to_project_button.pack(pady=5, anchor="w")

# Exit Section
exit_label = tk.Label(content_frame, text="To quit, click below")
exit_label.pack(anchor="w")

exit_button = tk.Button(content_frame, text="Exit Application", command=exit_application, bg="red")
exit_button.pack(pady=10, anchor="w")

# Start the tkinter event loop
window.mainloop()



Thanks a bunch!
Pavi.
minimax Posted - 08/23/2023 : 02:01:41 AM
Hi Pavi,

We released originpro v1.1.8, which we hope fixes the hang issue.
https://pypi.org/project/originpro/1.1.8/

Would you mind to upgrade and check if there is still problem?
pavi-chem Posted - 08/22/2023 : 09:33:42 AM
Hi minimax,

Thanks for the suggestion to use .quit(), I have changed the code accordingly. Made this code with amateur python knowledge, forums help and ChatGPT. so, thank you for your quick responses.

Appreciate this forum :)

Thanks a bunch!
Pavi.
minimax Posted - 08/22/2023 : 04:52:55 AM
Hi Pavi,

We can now reproduce the problem, will take a look and get back to you soon. (record ID: ORG-27617)


PS, aside from the hang issue, we think it is not very proper to use destroy() method to end the tk dialog.

Instead, we suggest use quit(), like

def exit_application():
    try:
        # Close the active Origin project
        op.exit()
        #window.destroy()  # Close the main GUI window, which ends the tkinter event loop
        window.quit()

It is not related to the hang issue, we just noticed it when running the script.
YimingChen Posted - 08/21/2023 : 4:24:02 PM
I have tried step 2 to process the background and was able to export the result to an Excel sheet. Could you open the Python file in Origin Code Builder window, and insert a breakpoint within the bg_processing() function? Run the code and observe at which line it becomes unresponsive. Thank you.
https://www.originlab.com/doc/python/Running_Python_Code#From_Code_Builder


James

The Origin Forum © 2020 Originlab Corporation Go To Top Of Page
Snitz Forums 2000