Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将tkinter上文本框中的文本保存到文本文件中?_Python_Python 3.x_Tkinter_Tk_Ttk - Fatal编程技术网

Python 如何将tkinter上文本框中的文本保存到文本文件中?

Python 如何将tkinter上文本框中的文本保存到文本文件中?,python,python-3.x,tkinter,tk,ttk,Python,Python 3.x,Tkinter,Tk,Ttk,又一个noob再次请求帮助。这是我的密码。我正在尝试从文本框中收集文本。我已经搜索了如何保存它的解决方案,但它只是打开了保存文件,没有保存任何内容。我试图做的是在我使用我的小部件将数据列为保存文件后将文本保存到一个文件中,但遗憾的是,这是唯一对我不起作用的事情。也许我在试图拯救它的过程中做错了什么。我正在尝试修复我的函数保存文件\u txt class OrderWindow: def __init__(self, master): self.master = mast

又一个noob再次请求帮助。这是我的密码。我正在尝试从文本框中收集文本。我已经搜索了如何保存它的解决方案,但它只是打开了保存文件,没有保存任何内容。我试图做的是在我使用我的小部件将数据列为保存文件后将文本保存到一个文件中,但遗憾的是,这是唯一对我不起作用的事情。也许我在试图拯救它的过程中做错了什么。我正在尝试修复我的函数
保存文件\u 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)

我也是一个新手,但是在tkinter中使用一个类来创建一个新窗口似乎有点疯狂

也许可以尝试通过使用tkinter.Toplevel()来简化,然后从那里获取逻辑函数。无需如此多的自我呼叫,只需在提交和保存后更新表单即可。下面是一个简化的例子

# 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()
启动:(主窗口)

点击:(顶层)

输出:(txt_文件)

希望这有点帮助。有时候,答案就在我的项目的嵌套混乱中。

没有用于字符串(
filetext
)的
save()
函数。您需要在写入模式下打开所选文件(
保存_text
),并将文本内容保存到文件中:

def保存文件(self):
filetext=self.basket\u textbox.get(“1.0”,“end-1c”)
保存text=filedialog.asksaveasfilename(
defaultextension=“txt”,
文件类型=[(“文本文件”,“*.txt”),(“所有文件”,“**”)],
)
如果保存文本:
打开时(将文本“w”另存为f):
f、 写入(文件文本)
没有可用于保存数据的
save()
方法;相反,您必须“手动”保存数据。可以使用以下命令保存数据:

open(文件名'w')。write(数据)