Advertisement
Python253

custom_input_box_to_json

May 23rd, 2024
658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.77 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: custom_input_box_to_json.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script creates a custom input box using Tkinter.
  10.    - Users can enter data in the input box and press Enter to add each entry.
  11.    - Once all data has been entered, users can click the Submit button to finish.
  12.    - It provides an option to save the entered data to a JSON file named "output_data_entry.json" in the current working directory.
  13.  
  14. Requirements:
  15.    - Python 3.x
  16.    - Tkinter library
  17.  
  18. Functions:
  19.    - show_custom_input_box():
  20.        Displays the custom input box and returns the user inputs as a formatted list.
  21.  
  22.    - print_user_inputs(inputs):
  23.        Prints the user inputs in json format.
  24.  
  25.    - save_user_inputs_as_json(inputs):
  26.        Saves the user inputs to a JSON file named "output_data_entry.json" in the current working directory.
  27.  
  28. Usage:
  29.    - Run the script.
  30.    - Enter data in the input box and press Enter for each entry.
  31.    - Click the Submit button when all data has been entered.
  32.  
  33. Example Output:
  34.  
  35.    {
  36.        "1": "First input",
  37.        "2": "Second input",
  38.        "3": "Third input"
  39.    }
  40.  
  41. Additional Notes:
  42.    - The script provides a simple way to gather multiple inputs from the user using a graphical interface.
  43. """
  44.  
  45. import tkinter as tk
  46. import json
  47.  
  48. class CustomInputBox:
  49.     def __init__(self, root):
  50.         """
  51.        Initialize the custom input box.
  52.  
  53.        Parameters:
  54.            root (Tk): The root window.
  55.        """
  56.         self.root = root
  57.         self.root.title("Data Entry Form")
  58.         self.root.geometry("400x150")
  59.         self.root.resizable(False, False)
  60.         self.root.eval('tk::PlaceWindow . center')
  61.  
  62.         self.label = tk.Label(root, text="Enter Data Below & Press 'Enter' To Add Each Entry.\nClick 'Submit' When All Data Has Been Entered:")
  63.         self.label.pack(pady=10)
  64.  
  65.         self.text_box = tk.Entry(root, width=40)
  66.         self.text_box.pack(pady=5)
  67.         self.text_box.focus_set()
  68.         self.text_box.bind("<Return>", lambda event: self.add_input())
  69.  
  70.         self.button_frame = tk.Frame(root)
  71.         self.button_frame.pack(pady=20)
  72.  
  73.         self.submit_button = tk.Button(self.button_frame, text="Submit", width=10, command=self.submit)
  74.         self.submit_button.grid(row=0, column=0, padx=5)
  75.  
  76.         self.exit_button = tk.Button(self.button_frame, text="Exit", width=10, command=self.exit_program)
  77.         self.exit_button.grid(row=0, column=1, padx=5)
  78.  
  79.         self.inputs = []
  80.  
  81.     def add_input(self):
  82.         """
  83.        Add input from the text box to the inputs list and clear the text box.
  84.        """
  85.         input_text = self.text_box.get()
  86.         if input_text:
  87.             self.inputs.append(input_text)
  88.             self.text_box.delete(0, tk.END)
  89.             self.text_box.focus_set()
  90.  
  91.     def submit(self):
  92.         """
  93.        Add the final input if any and close the input box.
  94.        """
  95.         if self.text_box.get():
  96.             self.inputs.append(self.text_box.get())
  97.         self.root.destroy()
  98.  
  99.     def exit_program(self):
  100.         """
  101.        Exit the program.
  102.        """
  103.         self.root.destroy()
  104.  
  105. def show_custom_input_box():
  106.     """
  107.    Display the custom input box and return the user inputs.
  108.  
  109.    Returns:
  110.        list: The user inputs.
  111.    """
  112.     root = tk.Tk()
  113.     input_box = CustomInputBox(root)
  114.     root.mainloop()
  115.     return input_box.inputs
  116.  
  117. def print_user_inputs(inputs):
  118.     """
  119.    Print the user inputs in a formatted manner.
  120.  
  121.    Parameters:
  122.        inputs (list): The list of user inputs.
  123.    """
  124.     if inputs:
  125.         print("User inputs:")
  126.         for i, input_data in enumerate(inputs, start=1):
  127.             print(f"{i}: {input_data}")
  128.     else:
  129.         print("User cancelled the input.\n\nExiting Program... Goodbye!\n")
  130.  
  131. def save_user_inputs_as_json(inputs):
  132.     """
  133.    Save the user inputs to a JSON file named "output_data_entry.json".
  134.  
  135.    Parameters:
  136.        inputs (list): The list of user inputs.
  137.    """
  138.     with open("output_data_entry.txt", "w", encoding="utf-8") as file:
  139.         json.dump({str(i+1): input_data for i, input_data in enumerate(inputs)}, file, indent=4)
  140.  
  141. if __name__ == "__main__":
  142.     user_inputs = show_custom_input_box()
  143.     print_user_inputs(user_inputs)
  144.     if user_inputs:
  145.         choice = input("\nDo you want to save the data to a file?\n\n1: Yes\n2: No\n\nMake your selection (1 or 2): ")
  146.         if choice == '1':
  147.             save_user_inputs_as_json(user_inputs)
  148.             print("\nData saved to 'output_data_entry.json'.\n\nExiting Program... Goodbye!\n")
  149.         elif choice == '2':
  150.             print("Data not saved.")
  151.         else:
  152.             print("Invalid input. Data not saved.")
  153.  
  154.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement