Home > OS >  Saving file in tkinter not getting saved properly
Saving file in tkinter not getting saved properly

Time:10-02

I wanted to save all the text which I enter in the listbox. "my_list" is the listbox over here. But when I save my file, I get the output in the form of a tuple, as shown below:

("Some","Random","Values")

Below is the python code. I have added comments to it. The add_items function adds data into the entry box. The savefile function is supposed to save all the data entered in the entry box (each entry must be in a new line)

from tkinter import *
from tkinter.font import Font
from tkinter import filedialog


root = Tk()
root.title('TODO List!')
root.geometry("500x500")
name = StringVar()

############### Fonts ################

my_font = Font(
    family="Brush Script MT",
    size=30,
    weight="bold")

################# Frame #################
my_frame = Frame(root)
my_frame.pack(pady=10)


################# List Box #############
my_list = Listbox(my_frame,
           font=my_font,
           width=25,
           height=5,
           bg="SystemButtonFace",
           bd=0,
           fg="#464646",
           highlightthickness=0,
           selectbackground="grey",
           activestyle="none")

my_list.pack(side=LEFT, fill=BOTH)

############### Dummy List ##################

#stuff = ["Do daily Checkin","Do Event checkin","Complete Daily Task","Complete Weekly Task","Take a break"]

############# Add dummmy list to list box ##############
#for item in stuff:
 #   my_list.insert(END, item)
    
################# Ceate Scrollbar ###########################
my_scrollbar= Scrollbar(my_frame)
my_scrollbar.pack(side=RIGHT, fill=BOTH)

#################### Add Scrollbar ######################
my_list.config(yscrollcommand=my_scrollbar.set)
my_scrollbar.config(command=my_list.yview)

################### ADD item entry box#################
my_entry = Entry(root, font=("Helvetica", 24),width=24, textvariable=name)
my_entry.pack(pady=20)

######################## Crete button frame ##########
button_frame=Frame(root)
button_frame.pack(pady=20)


##################### Funnctions ###################


def add_item():
    my_list.insert(END, my_entry.get())
    name1 = name.get()
    my_entry.delete(0, END)

 

def saveFile():
    file = filedialog.asksaveasfile(initialdir="C:\\Users\\Deepu John\\OneDrive\\Deepu 2020\\Projects\\rough",
                                    defaultextension='.txt',
                                    filetypes=[
                                        ("Text file",".txt"),
                                        ("HTML file", ".html"),
                                        ("All files", ".*"),
                                    ])
    if file is None:
        return
    #fob = open(file,'w')    
    filetext = str(my_list.get('1', 'end'))
    file.write(filetext)
    file.close()
    
def delete_list():
    my_list.delete(0,END)


################# Add Buttons ################


add_button = Button(button_frame, text="Add Item",command=add_item)
save_button = Button(button_frame, text="Save",width=8,command=saveFile)

add_button.grid(row=0,column=1, padx=20)  
save_button.grid(row=0,column=2,padx=5) 

root.mainloop()      

I want each value to be in a new line. Like this:

Some
Random
Values

How do I do this?

CodePudding user response:

The main part is that listbox.get(first, last) returns a tuple so you could use .join string method to create a string where each item in the tuple is separated by the given string:

'\n'.join(listbox.get('0', 'end'))

Complete example:

from tkinter import Tk, Entry, Listbox, Button


def add_item(event=None):
    item = entry.get() or None
    entry.delete('0', 'end')
    listbox.insert('end', item)


def save_listbox():
    """the main part:
    as `listbox.get(first, last)` returns a tuple
    one can simply use the `.join` method
    to create a string where each item is separated
    by the given string"""
    
    data = '\n'.join(listbox.get('0', 'end'))
    with open('my_list.txt', 'w') as file:
        file.write(data)


root = Tk()

entry = Entry(root)
entry.pack(padx=10, pady=10)
entry.bind('<Return>', add_item)

listbox = Listbox(root)
listbox.pack(padx=10, pady=10)

button = Button(root, text='Save', command=save_listbox)
button.pack(padx=10, pady=10)

root.mainloop()

Also:
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.

  • Related