-2

Another noob asking for help again. Here is my code. I am trying to collect my text from the textbox. I have searched for the solution on how to save it but it just opens the save file and doesn't save anything. What I am trying to do is to save the text into a file after I've listed data using my widgets as a save file but sadly, that's the only thing that does not work for me. Perhaps I did something wrong in trying to save it. I am trying to fix my function saving_file_txt.

class OrderWindow:

    def __init__(self, master):
        self.master = master
        self.master.title("Order Window Page")
        self.master.geometry("1500x800")
        self.master.configure(background="azure")
        self.frame = Frame(self.master)
        self.frame.pack()

        # Placeholder for the information when ordering

        self.prod_no_var = StringVar()  # Product No input placeholder
        self.product_name_var = StringVar()  # Product Name input placeholder
        self.quantity_var = StringVar()  # Quantity input placeholder
        self.prod_cost_var = StringVar()  # Product Cost input placeholder
        self.subtotal_var = StringVar()  # Subtotal input placeholder

        ######################### Ordering Frame ################################
        # Frame 1 - Ordering Details

        self.order_detail_frame = Frame(self.frame, bg="azure")
        self.order_detail_frame.grid(row=1, column=0)

        self.basket_frame = Frame(self.frame)
        self.basket_frame.grid(row=1, column=1)

        self.heading = Label(self.order_detail_frame, text="AAT Shopping Application",
                             font=("arial", 15, "bold")).grid(row=0, column=0, ipadx=25)

        self.order_detail_lblFrame = LabelFrame(self.order_detail_frame, text="Order Details")
        self.order_detail_lblFrame.grid(row=1, column=0, ipady=50)

        self.basket_heading = Label(self.basket_frame,
                                    text="Product No\t\tProduct Name\t\tProduct Quantity\t\tProduct Price\t\tSubtotal"
                                    ).grid(row=0, column=0, columnspan=4, sticky="ne", ipadx=10)

        self.basket_textbox = Text(self.basket_frame)
        self.basket_textbox.grid(row=1, column=0, columnspan=4)

        ###########################Labels#############################
        self.order_no = Label(self.order_detail_lblFrame, text="Order No").grid(row=0, column=0)
        self.prod_name_lbl = Label(self.order_detail_lblFrame, text="Product Name").grid(row=1, column=0)
        self.prod_qty_lbl = Label(self.order_detail_lblFrame, text="Quantity").grid(row=2, column=0)
        self.prod_cost_lbl = Label(self.order_detail_lblFrame, text="Product Cost").grid(row=3, column=0)

        self.subtotal_lbl = Label(self.order_detail_lblFrame, text="Sub Total").grid(row=4, column=0)

        # Entry and Option Menu for ordering

        ########################### Product Combo Box #############################
        self.prod_name_cb = ttk.Combobox(self.order_detail_lblFrame, textvariable=self.product_name_var)
        self.prod_name_cb.grid(row=1, column=1, padx=35)
        self.prod_name_cb["value"] = ("", "Gundam", "Starwars", "Paw Patrol", "Peppa Pig", "Cars Disney", "Teddy Bear")
        self.prod_name_cb.current(0)

        ########################## Entry Box #############################

        self.prod_no_entry = Entry(self.order_detail_lblFrame, textvariable=self.prod_no_var)
        self.prod_no_entry.grid(row=0, column=1)

        self.order_qty_entry = Entry(self.order_detail_lblFrame, textvariable=self.quantity_var)
        self.order_qty_entry.grid(row=2, column=1)

        self.order_cost_entry = Entry(self.order_detail_lblFrame, textvariable=self.prod_cost_var, state="disabled")
        self.order_cost_entry.grid(row=3, column=1)

        self.order_subtotal_entry = Entry(self.order_detail_lblFrame, textvariable=self.subtotal_var,
                                          state="disabled")
        self.order_subtotal_entry.grid(row=4, column=1)  # Repeated line because it returns none value which gives error

        ########################## Buttons #############################
        self.add_button = Button(self.order_detail_lblFrame, text="Add", command=self.add_item).grid(row=6, column=0)
        self.delete_button = Button(self.order_detail_lblFrame, text="Delete", command=self.delete_item).grid(row=7,
                                                                                                              column=0)
        self.reset_button = Button(self.order_detail_lblFrame, text="Reset", command=self.reset_entry).grid(row=8,
                                                                                                            column=0)
        self.category_button = Button(self.order_detail_lblFrame, text="View products",
                                      command=self.open_catalogue).grid(row=9, column=0)

        self.save_basketfile_button = Button(self.order_detail_lblFrame, text="Save Reciept",
                                             command=self.saving_file_txt
                                             ).grid(row=6, column=1)

        self.pay_button = Button(self.order_detail_lblFrame, text="Checkout",
                                 command=self.checkout_item).grid(row=7, column=1)
        self.screenshot_button = Button(self.order_detail_lblFrame, text="Screenshot Window",
                                        command=self.screenshoot_screen).grid(row=8, column=1)
        self.exit_window_button = Button(self.order_detail_lblFrame, text="Exit",
                                         command=self.exit_window).grid(row=9, column=1)

    def add_item(self):
        global total
        item_dict = {"": 0, "Gundam": 10, "Starwars": 20, "Paw Patrol": 30, "Peppa Pig": 15, "Cars Disney": 15,
                     "Teddy Bear": 10}
        order_no = self.prod_no_var.get()
        item = self.product_name_var.get()
        price = (self.prod_cost_var.get())
        qty = int(self.quantity_var.get())

        for product, cost in item_dict.items():
            if item == product:
                price = cost
                total = round(price * qty, 2)

        self.prod_no_var.set(int(order_no) + 1)
        self.prod_cost_var.set("£" + str(price))
        self.subtotal_var.set("£" + str(total))

        self.basket_textbox.insert(END, self.prod_no_var.get() + "\t\t" + self.product_name_var.get() + "\t\t\t" +
                                   self.quantity_var.get() + "\t\t" + self.prod_cost_var.get() + "\t\t" +
                                   self.subtotal_var.get() + "\n")

    def delete_item(self):
        self.basket_textbox.delete("1.0", "2.0")

    def reset_entry(self):
        self.prod_no_var.set("")
        self.product_name_var.set("")
        self.quantity_var.set("")
        self.prod_cost_var.set("")
        self.subtotal_var.set("")

    def checkout_item(self):
        self.newWindow = Toplevel(self.master)
        self.app = PaymentWindow(self.newWindow)

    def open_catalogue(self):
        self.newWindow = Toplevel(self.master)
        self.app = CatalogueWindow(self.newWindow)

    def exit_window(self):
        self.master.destroy()

    def screenshoot_screen(self):
        window_screenshot = pyautogui.screenshot()

        file_path = filedialog.asksaveasfilename(defaultextension=".png")

        window_screenshot.save(file_path)

    def saving_file_txt(self):
        filetext = self.basket_textbox.get("1.0", "end-1c")
        save_text = filedialog.asksaveasfilename(
            defaultextension="txt",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
        )

        filetext.save(save_text)
acw1668
  • 40,144
  • 5
  • 22
  • 34
Markkkk
  • 1
  • 1

3 Answers3

0

I too am a newb , but this seems crazy confusing to utilize a class for a new window in tkinter.

Maybe try to simplify by utilizing tkinter.Toplevel() and then sourcing your logical functions from there. eliminate the need for so many self calls and just update forms after submission and save. A simplified example below.

# import libraries (i use as tk to reduce the full import on launch)
import tkinter as tk

client_orders = [] # List of orders

def new_order_popup():
    new_order_window.deiconify() # used to open the new order window (toplevel window)

class NEW_ORDER: # new order class, simplified for example)
    def __init__(self, product_num, product_name, product_price):
        self.product_num = product_num
        self.product_name = product_name
        self.product_price = product_price


def new_order(product_num, product_name, product_price): # creates each new order when 
called.
    new_order_window.deiconify()
    input_product_num = pro_num_entry.get()
    input_product_name = pro_name_entry.get()
    input_product_price = float(pro_price_entry.get())

    newOrder = NEW_ORDER(input_product_num, input_product_name, input_product_price)
    return newOrder


def sub_(): # action when button pressed for submit/save

    customer_order = new_order(product_num=str, product_name=str, product_price=float)
    price_str = str(customer_order.product_price)
    client_orders.append(customer_order)
    order_string = (customer_order.product_num,' : ', customer_order.product_name,' : 
    ', price_str,'\n')
    print(order_string)
    txt_file = open(f'text_doc.txt', 'a')
    txt_file.writelines(order_string)
    txt_file.close()


def sub_ex(): # same as other button but closes toplevel window.
    customer_order = new_order(product_num=str, product_name=str, product_price=float)
    price_str = str(customer_order.product_price)
    client_orders.append(customer_order)
    order_string = (customer_order.product_num, ' : ', customer_order.product_name, ' 
    : ', price_str, '\n')
    print(order_string)

    txt_file = open(f'text_doc.txt', 'a')
    txt_file.writelines(order_string)
    txt_file.close()
    new_order_window.withdraw()

#main window tkinter  code.  (at bottom eleviates complicated poiubters abd calls)
main = tk.Tk()

main.geometry('300x100')
main.title('Some Ordering System')
#button that does something
new_order_button = tk.Button(main)
new_order_button.configure(text='NewOrder', command = lambda: new_order_popup())
new_order_button.pack(pady=25)

#secondary window
new_order_window = tk.Toplevel(main)
new_order_window.geometry('300x200')
new_order_window.withdraw()

list_label = tk.Label(new_order_window)
list_label.configure(text='Prod. Num.\nProd. Name.\nProd. Price.')
list_label.place(anchor=tk.NW, x=15, y=15)

pro_num_entry = tk.Entry(new_order_window)
pro_num_entry.configure(width=20)
pro_num_entry.place(anchor=tk.NW, x=100, y=15)

pro_name_entry = tk.Entry(new_order_window)
pro_name_entry.configure(width=20)
pro_name_entry.place(anchor=tk.NW, x=100, y=35)

pro_price_entry = tk.Entry(new_order_window)
pro_price_entry.configure(width=20)
pro_price_entry.place(anchor=tk.NW, x=100, y=55)

submit_button = tk.Button(new_order_window)

submit_button.configure(text='Submit', command = lambda: sub_())
submit_button.place(anchor=tk.NW, x=35, y=100)

submit_exit_button = tk.Button(new_order_window)

submit_exit_button.configure(text='Submit and exit', command = lambda: sub_ex())
submit_exit_button.place(anchor=tk.NW, x=100, y=100)

main.mainloop()

launch: (mainwindow) enter image description here

click:(toplevel) enter image description here

output:(txt_file) enter image description here

Hope this helps a bit. sometimes the answer is in the nested mess with my projects.

Muzeeto
  • 11
  • 4
0

There is no save() function for string (filetext). You need to open the selected file (save_text) in write mode and save the text content to the file:

    def saving_file_txt(self):
        filetext = self.basket_textbox.get("1.0", "end-1c")
        save_text = filedialog.asksaveasfilename(
            defaultextension="txt",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
        )
        if save_text:
            with open(save_text, "w") as f:
                f.write(filetext)
acw1668
  • 40,144
  • 5
  • 22
  • 34
0

There's no save() method that can be used to save data; instead, you have to "manually" save the data. You can use the following commands to save the data:

open(filename, 'w').write(data)
Geetansh G
  • 17
  • 7