[英]Writing to a .txt file using Python and SQLite3
我目前正在從事一個學校項目,我必須使用 Python、Tkinter 和 SQLite3 創建一個帶有 GUI 的數據庫應用程序。 我正在嘗試創建一個 function ,用戶將在其中將 OrderID 鍵入表單,並且將從數據庫文件中獲取具有相應 OrderID 的訂單詳細信息並插入到文本文件中。 我在嘗試運行代碼時收到以下錯誤:
File "c:\Users\Ryan\OneDrive - C2k\A2 2020-2021\Computer Science\A2 Unit 5\Code\OrderForm.py", line 149, in PrintOrder
write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))
TypeError: write() takes exactly one argument (2 given)
我的代碼片段和表單的屏幕截圖附在下面:
def PrintOrder(self):
orderid = self.OrderIDEntry.get()
productid = self.ProductIDEntry.get()
quantity = self.QuantityEntry.get()
with sqlite3.connect("LeeOpt.db") as db:
cursor = db.cursor()
search_order = ('''SELECT * FROM Orders WHERE OrderID = ?''')
cursor.execute(search_order, [(orderid)])
results = cursor.fetchall()
if results:
for i in results:
write = open("orderinvoice.txt","w")
write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))
tkinter.messagebox.showinfo("Notification","Invoice generated successfully.")
self.ClearEntries()
else:
tkinter.messagebox.showerror("Error", "No order was found with this OrderID, please try again.")
self.ClearEntries()
您的問題/錯誤在於write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))
行。 write.write()
中的逗號創建 2 個 arguments,其中 write-function 只需要一個(要寫入的文本)。 我已經修改了您的代碼,因此它仍然將所有結果寫入單獨的行。
def PrintOrder(self):
orderid = self.OrderIDEntry.get()
productid = self.ProductIDEntry.get()
quantity = self.QuantityEntry.get()
with sqlite3.connect("LeeOpt.db") as db:
cursor = db.cursor()
search_order = ('''SELECT * FROM Orders WHERE OrderID = ?''')
cursor.execute(search_order, [(orderid)])
results = cursor.fetchall()
if results:
for i in results:
write = open("orderinvoice.txt","w")
write.write("-----CUSTOMER INVOICE-----")
for x in results:
write.write(str(x))
tkinter.messagebox.showinfo("Notification","Invoice generated successfully.")
self.ClearEntries()
else:
tkinter.messagebox.showerror("Error", "No order was found with this OrderID, please try again.")
self.ClearEntries()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.