[英]Need help writing user input into new row on CSV file in python
這是我的代碼:
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import tkinter.ttk as ttk
import csv
import pandas as pd
pd.options.display.max_columns = 20
import sqlite3
connection = sqlite3.connect('salesmanage.db')
frame_styles = {"relief": "groove",
"bd": 3, "bg": "#BEB2A7",
"fg": "#073bb3", "font": ("Arial", 9, "bold")}
class LoginPage(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self, bg="#708090", height=750, width=1000) # this is the background
main_frame.pack(fill="both", expand="true")
self.geometry("626x431") # Sets window size to 626w x 431h pixels
self.resizable(0, 0) # This prevents any resizing of the screen
title_styles = {"font": ("Trebuchet MS Bold", 16), "background": "blue"}
text_styles = {"font": ("Verdana", 14),
"background": "blue",
"foreground": "#E1FFFF"}
frame_login = tk.Frame(main_frame, bg="blue", relief="groove", bd=2) # this is the frame that holds all the login details and buttons
frame_login.place(rely=0.30, relx=0.17, height=136, width=500)
label_title = tk.Label(frame_login, title_styles, text="Login Page")
label_title.grid(row=0, column=1, columnspan=1)
label_user = tk.Label(frame_login, text_styles, text="Username:")
label_user.grid(row=1, column=0)
label_pw = tk.Label(frame_login, text_styles, text="Password:")
label_pw.grid(row=2, column=0)
entry_user = ttk.Entry(frame_login, width=45, cursor="xterm")
entry_user.grid(row=1, column=1)
entry_pw = ttk.Entry(frame_login, width=45, cursor="xterm", show="*")
entry_pw.grid(row=2, column=1)
button = ttk.Button(frame_login, text="Login", command=lambda: getlogin())
button.place(rely=0.70, relx=0.50)
signup_btn = ttk.Button(frame_login, text="Register", command=lambda: get_signup())
signup_btn.place(rely=0.70, relx=0.75)
def get_signup():
SignupPage()
def getlogin():
username = entry_user.get()
password = entry_pw.get()
# if your want to run the script as it is set validation = True
validation = validate(username, password)
if validation:
tk.messagebox.showinfo("Login Successful",
"Welcome {}".format(username))
root.deiconify()
top.destroy()
else:
tk.messagebox.showerror("Information", "The Username or Password you have entered are incorrect ")
def validate(username, password):
# Checks the text file for a username/password combination.
try:
with open("credentials.txt", "r") as credentials:
for line in credentials:
line = line.split(",")
if line[1] == username and line[3] == password:
return True
return False
except FileNotFoundError:
print("You need to Register first or amend Line 71 to if True:")
return False
class SignupPage(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self, bg="#3F6BAA", height=150, width=250)
# pack_propagate prevents the window resizing to match the widgets
main_frame.pack_propagate(0)
main_frame.pack(fill="both", expand="true")
self.geometry("250x150")
self.resizable(0, 0)
self.title("Registration")
text_styles = {"font": ("Verdana", 10),
"background": "#3F6BAA",
"foreground": "#E1FFFF"}
label_user = tk.Label(main_frame, text_styles, text="New Username:")
label_user.grid(row=1, column=0)
label_pw = tk.Label(main_frame, text_styles, text="New Password:")
label_pw.grid(row=2, column=0)
entry_user = ttk.Entry(main_frame, width=20, cursor="xterm")
entry_user.grid(row=1, column=1)
entry_pw = ttk.Entry(main_frame, width=20, cursor="xterm", show="*")
entry_pw.grid(row=2, column=1)
button = ttk.Button(main_frame, text="Create Account", command=lambda: signup())
button.grid(row=4, column=1)
def signup():
# Creates a text file with the Username and password
user = entry_user.get()
pw = entry_pw.get()
validation = validate_user(user)
if not validation:
tk.messagebox.showerror("Information", "That Username already exists")
else:
if len(pw) > 3:
credentials = open("credentials.txt", "a")
credentials.write(f"Username,{user},Password,{pw},\n")
credentials.close()
tk.messagebox.showinfo("Information", "Your account details have been stored.")
SignupPage.destroy(self)
else:
tk.messagebox.showerror("Information", "Your password needs to be longer than 3 values.")
def validate_user(username):
# Checks the text file for a username/password combination.
try:
with open("credentials.txt", "r") as credentials:
for line in credentials:
line = line.split(",")
if line[1] == username:
return False
return True
except FileNotFoundError:
return True
class MenuBar(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
menu_file = tk.Menu(self, tearoff=0)
self.add_cascade(label="Menu1", menu=menu_file)
menu_file.add_command(label="All Widgets", command=lambda: parent.show_frame(Some_Widgets))
menu_file.add_separator()
menu_file.add_command(label="Exit Application", command=lambda: parent.Quit_application())
menu_help = tk.Menu(self, tearoff=0)
self.add_cascade(label="Menu6", menu=menu_help)
menu_help.add_command(label="Open New Window", command=lambda: parent.OpenNewWindow())
class MyApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self, bg="#84CEEB", height=1200, width=1600)
main_frame.pack_propagate(0)
main_frame.pack(fill="both", expand="true")
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
# self.resizable(0, 0) prevents the app from being resized
# self.geometry("1024x600") fixes the applications size
self.frames = {}
pages = (Some_Widgets, PageOne, PageTwo, PageThree, PageFour)
for F in pages:
frame = F(main_frame, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Some_Widgets)
menubar = MenuBar(self)
tk.Tk.config(self, menu=menubar)
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
def OpenNewWindow(self):
OpenNewWindow()
def Quit_application(self):
self.destroy()
class GUI(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.main_frame = tk.Frame(self, bg="#BEB2A7", height=1000, width=2500)
# self.main_frame.pack_propagate(0)
self.main_frame.pack(fill="both", expand="true")
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
class Some_Widgets(GUI): # inherits from the GUI class
def __init__(self, parent, controller):
GUI.__init__(self, parent)
frame1 = tk.LabelFrame(self, frame_styles, text="Sales Data Table")
frame1.place(rely=0.05, relx=0.02, height=500, width=2300)
frame2 = tk.LabelFrame(self, frame_styles, text="Add Item To Inventory")
frame2.place(rely=0.55, relx=0.02, height=250, width=2300)
# This is a treeview.
tv1 = ttk.Treeview(frame1, columns=("Date", "Device", "Cost", "IMEI/Serial", "Status", "Sale Location", "Listing Location", "Final Price", "Fees + Shipping + Duration Fee", "Profit", "Notes", "Shipping"))
column_list_account = ["Date", "Device", "Cost", "IMEI/Serial", "Status", "Sale Location", "Listing Location", "Final Price", "Fees + Shipping + Duration Fee", "Profit", "Notes", "Shipping"]
tv1["show"] = "headings" # removes empty column
tv1['columns'] = column_list_account
for column in column_list_account:
tv1.heading(column, text=column)
tv1.column(column, width=100)
tv1.place(relheight=1, relwidth=0.995)
treescroll = tk.Scrollbar(frame1)
treescroll.configure(command=tv1.yview)
tv1.configure(yscrollcommand=treescroll.set)
treescroll.pack(side="right", fill="y")
def Load_data():
with open('salesinfobuysafetech.csv') as f:
reader = csv.reader(f)
for row in reader:
tv1.insert("", 'end', values=row)
def Refresh_data():
# Deletes the data in the current treeview and reinserts it.
tv1.delete(*tv1.get_children()) # *=splat operator
Load_data()
Load_data()
additem_btn1 = ttk.Button(frame2, text="Add Item", command=lambda: get_item())
additem_btn1.place(rely=.5, relx=0.5)
def get_item():
get_itempage()
class get_itempage(tk.Tk): # inherits from the GUI class
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
new_frame = tk.Frame(self, bg="#3F6BAA", height=300, width=750)
# pack_propagate prevents the window resizing to match the widgets
new_frame.pack_propagate(0)
new_frame.pack(fill="both", expand="true")
self.geometry("=300x500")
self.resizable(0, 0)
self.title("Log New Item Page")
text_styles = {"font": ("Verdana", 10),
"background": "#3F6BAA",
"foreground": "#E1FFFF"}
label_user1 = tk.Label(new_frame, text_styles, text="Enter new item: Format=***,***,***")
label_user1.grid(row=1, column=0)
entry_user1 = ttk.Entry(new_frame, width=20, cursor="xterm")
entry_user1.grid(row=2, column=0)
button1 = ttk.Button(new_frame, text="Log Item", command=lambda: newitem())
button1.grid(row=3, column=0)
def newitem():
# Creates a text file with the Username and password
item = (entry_user1.get())
with open('salesinfobuysafetech.csv', "a") as itemlist:
w = csv.writer(itemlist, quoting=csv.QUOTE_ALL, delimiter=',')
w.writerow(item)
itemlist.close()
tk.messagebox.showinfo("Your item has been logged")
get_itempage.destroy(self)
class PageOne(GUI):
def __init__(self, parent, controller):
GUI.__init__(self, parent)
label1 = tk.Label(self.main_frame, font=("Verdana", 20), text="Page One")
label1.pack(side="top")
class PageThree(GUI):
def __init__(self, parent, controller):
GUI.__init__(self, parent)
label1 = tk.Label(self.main_frame, font=("Verdana", 20), text="Page Three")
label1.pack(side="top")
class PageFour(GUI):
def __init__(self, parent, controller):
GUI.__init__(self, parent)
label1 = tk.Label(self.main_frame, font=("Verdana", 20), text="Page Four")
label1.pack(side="top")
class PageTwo(GUI):
def __init__(self, parent, controller):
GUI.__init__(self, parent)
label1 = tk.Label(self.main_frame, font=("Verdana", 20), text="Page Two")
label1.pack(side="top")
class OpenNewWindow(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self)
main_frame.pack_propagate(0)
main_frame.pack(fill="both", expand="true")
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
self.title("Here is the Title of the Window")
self.geometry("500x500")
self.resizable(0, 0)
frame1 = ttk.LabelFrame(main_frame, text="This is a ttk LabelFrame")
frame1.pack(expand=True, fill="both")
label1 = tk.Label(frame1, font=("Verdana", 20), text="OpenNewWindow Page")
label1.pack(side="top")
top = LoginPage()
top.title("Login Page")
root = MyApp()
root.withdraw()
root.title("Sales Management System BST")
if __name__ == '__main__':
root.mainloop()
整個代碼和應用程序運行良好。 但是,它沒有將輸入正確寫入 csv 文件的行中。
例如,如果用戶輸入“測試”作為他們的輸入。 它將作為 t,e,s,t 輸入到文件中。 如果用戶輸入 test,test,它會寫成 t,e,s,t,,t,e,s,t,。 基本上我需要它接受, , , , , , , , , , , ,*** 的格式。 輸入寫入的數據,以便可以將其讀取到 GUI 上的 12 列樹形表中。 它可能非常簡單,我錯過了任何幫助都會很棒。
這是給我帶來麻煩的代碼。
class get_itempage(tk.Tk): # inherits from the GUI class
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
new_frame = tk.Frame(self, bg="#3F6BAA", height=300, width=750)
# pack_propagate prevents the window resizing to match the widgets
new_frame.pack_propagate(0)
new_frame.pack(fill="both", expand="true")
self.geometry("=300x500")
self.resizable(0, 0)
self.title("Log New Item Page")
text_styles = {"font": ("Verdana", 10),
"background": "#3F6BAA",
"foreground": "#E1FFFF"}
label_user1 = tk.Label(new_frame, text_styles, text="Enter new item: Format=***,***,***")
label_user1.grid(row=1, column=0)
entry_user1 = ttk.Entry(new_frame, width=20, cursor="xterm")
entry_user1.grid(row=2, column=0)
button1 = ttk.Button(new_frame, text="Log Item", command=lambda: newitem())
button1.grid(row=3, column=0)
def newitem():
# Creates a text file with the Username and password
item = (entry_user1.get())
with open('salesinfobuysafetech.csv', "a") as itemlist:
w = csv.writer(itemlist, quoting=csv.QUOTE_ALL, delimiter=',')
w.writerow(item)
itemlist.close()
tk.messagebox.showinfo("Your item has been logged")
get_itempage.destroy(self)
您需要將輸入拆分為字段列表。
def newitem():
# Creates a text file with the Username and password
row = entry_user1.get().split(',')
with open('salesinfobuysafetech.csv', "a") as itemlist:
w = csv.writer(itemlist, quoting=csv.QUOTE_ALL, delimiter=',')
w.writerow(row)
tk.messagebox.showinfo("Your item has been logged")
get_itempage.destroy(self)
無需調用itemlist.close()
,當您離開with
塊時會自動完成(這是使用with
的全部意義)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.