Write data to file from a list, by tkinter entry - python

I can't figure out what I'm doing wrong here!
I trying to write/append data from tkinter entry to a txt file. The entries, goes to a list, that I will append to the text file. But it doesn't take my new entry, only my already defined text.
Here is my code:
from tkinter import *
root = Tk()
# Input
# -----------------------------------------------------
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
ivnget = ivn.get()
inputVarName.grid(row=0, column=0)
# Input
# -----------------------------------------------------
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
ivnget2 = ivn2.get()
inputVarName2.grid(row=1, column=0)
# Collecting data (entry)
# --------------------------------------------------------------------------------------
content_list = [ivnget, ivnget2]
# --------------------------------------------------------------------------------------
print("\n".join(content_list))
def writetofile():
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
# Button that applies entries to file
# --------------------------------------------------------------------------------------
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
# --------------------------------------------------------------------------------------
root.mainloop()

You have placed the get commands outside the function writetofile.
Try:
from tkinter import *
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop()

Related

Label Not Continually Updating Tkinter

I have read through several answers to similar topics but none of them are relevant to my situation, I am trying to display a list on a label and whenever the button is pressed to update the list the label should update as well but it only updates when submitbtn_name is clicked. Any help appreciated I am very new to Tkinter.
My Code:
from tkinter import *
root = Tk()
root.title("Path Creator")
root.geometry('1680x1080')
root['background'] = '#aaaaaa'
list_of_paths_list = []
path_list = []
name = Entry(root, width=400)
name.insert(0, "Name")
name.pack()
def add_name():
path_list.append(name.get())
list_label = Label(root, text="path name:" + str(path_list))
list_label.pack()
submitbtn_name = Button(root, text="submit name", command=add_name)
submitbtn_name.pack()
value1 = Entry(root, width=400)
value1.insert(0, "value1")
value1.pack()
distance1 = Entry(root, width=400)
distance1.insert(0, "distance1")
distance1.pack()
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text="current path: " + path_list)
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", )
submitbtn_pathpart.pack()
root.mainloop()
Using f-string format. Added command in submitbtn_pathpart
Snippet:
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text=f"current path:{path_list}")
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", command=submitbtn_value_dist )
submitbtn_pathpart.pack()
root.mainloop()
Output for name:
Output for value and distance:

How do I save my text from the textbox on tkinter to a text file?

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)
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)
click:(toplevel)
output:(txt_file)
Hope this helps a bit. sometimes the answer is in the nested mess with my projects.
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)
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)

python tkinter interface how to create a new to show txt file

I buid a code which takes python user input and insert it into a text file when pressing apply as shown in the picture bellow
and the text file will always be updated when the user inserts a new text, how to create an new button next to apply to show up to date text file to the user
and want prevent to enter the same text
example if the text file has a (go) the program do not enter (go) again
this is my code
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("help.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop()
To prevent a user from inserting the same text just empty the two entries, and you can check if entries are not empty before saving to a file.
You can use a top-level window to show the file content.
Check the following example:
from tkinter import Tk, Toplevel, Button, Entry, StringVar, Text, DISABLED, END, W, E
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
if any(content_list):
print("\n".join(content_list))
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
ivn2.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
root.mainloop()
Edited to answer #IbrahimOzaeri question in comments.
You can use tkFileDialog.askopenfilename to ask user to select a file:
from Tkinter import Tk
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
print (root.filename)
I was trying something same but with one output
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
root.geometry("500x300")
root.title("The Gatway company")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get()]
if any(content_list):
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
applyButton.config( height = 5, width = 10 )
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
showButton.config( height = 5, width = 10 )
root.mainloop()
it's same as your code but for one entry, I'm thinking to edit it in a such way that the user chooses the help.txt file like a file requester.

how to create a GUI using python to take user input and insert it into excel sheet

I want to create a python GUI with one user input which will be inserted to an excel sheet whenever the user Enters insert button, and another button called e.g Show words, which will read all the words which are inserted into the excel sheet, any ideas how to do that ?
the excel sheet shoud be like this
and the user interface should be something simple like this
some code that I created for GUI but its for text file not excel
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("help.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop() ```
sorry if its silly question but this will be my first python GUI program
You can create GUI using python tkinter, you can also create input fields using this library and accept the entered value. After this you can simple use python csv library to insert a record into sheet.
You can find more information about tkinter Here
Use this code to read data from test.txt (use your txt file) file, insert data into file also as you asked it will also check if same data exist. You can view the data by clicking on view data button.
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def printSomething():
with open('help.txt') as f:
r = f.read()
label = Label(root, text=r)
label.grid()
def checkdata():
with open('help.txt') as f:
r = f.read()
return r.split("\n")
def writetofile():
exist_data = checkdata()
content_list = [ivn.get(), ivn2.get()]
with open("help.txt", "a") as f:
for item in content_list:
if item in exist_data:
msg = "Already exist "+item
label = Label(root, text=msg)
label.grid()
elif not item in exist_data:
f.write("%s\n" % item)
applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)
veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)
root.mainloop()
Note: There are multiple ways to achieve this, one of them is this one.

How to attribute a button the function to get text from an output file?

What I need is to make the view orders button to get the text from the Customer.txt file and set it inside a textfield i made.
#make order,cancel,view
from tkinter import *
import tkinter.messagebox
root = Tk()
file = open("Customer.txt", "w")
def textW():
outFile = open("Customer.txt", "wt")
def CancelOrder():
outFile=open("Customer.txt", "w")
outFile.write("")
tkinter.messagebox.showinfo("Cancel Order", "Your order has been canceled")
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
#tViewOrder.set(test)
print (test)
#test.set(tViewOrder)
#outFile.close()
def MakeOrder():
outFile=open("Customer.txt", "w")
outFile.write("" + tMakeOrder.get())
tkinter.messagebox.showinfo("Make Order", "Order has been placed. Thank you!")
#Labels
lMakeOrder = Label(root, text="Make an order")
lViewOrder = Label(root, text="View Order")
#TextFields
tMakeOrder = Entry(root)
tViewOrder = Entry(root, state="disabled")
#Buttons
bMakeOrder = Button(root, text="Make order",bg="black",fg="green", command=MakeOrder)
bCancelOrder = Button(root, text="Cancel order",bg="black",fg="green", command=CancelOrder)
bViewOrder = Button(root, text="View orders",bg="black",fg="green", command=ViewOrder)
#Position
lMakeOrder.grid(row=0)
lViewOrder.grid(row=1)
tMakeOrder.grid(row=0, column=2)
tViewOrder.grid(row=1, column=2)
bMakeOrder.grid(row=4)
bViewOrder.grid(row=4, column=2)
bCancelOrder.grid(row=4, column=4)
#Window stuff
root.title("Sky is a shit name service - Customer")
root.geometry("300x300")
root.mainloop()
You can put text inside your Entry by calling insert function on it.
MyEntry.insert(POSITION, TEXT)
Oh and one more thing. You can't insert anything in the entry if it's disabled.
So here is your modified function:
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
tViewOrder['state'] = 'normal'
tViewOrder.delete(0, 'end') #Remove everything before
tViewOrder.insert(0, test)
tViewOrder['state'] = 'disabled'
outFile.close()

Categories

Resources