Home>

I want to save and read as a CSV file after manually writing to the GUI.

Currently, I put a list of no, first and last name, gender, and date of birth for the GUI display function, but I finally lost it.
I want to recreate the function to temporarily save the contents written manually (the state of toothlessness can also be saved).

If possible, I would like to just change the memory function part described later.

If there is nothing in the list box in that line, do nothing.
If i write a new one in the list box in that line, add it to each list.
If it has already been written in the list box in that line, it will be overwritten in each list (it will also overwrite the correction contents).
I want to rewrite the memory function to such a function, but it doesn't work.

Currently only invalid syntax is used.

Corresponding source code
Import #tkinter
import tkinter as tk
from tkinter import messagebox
#Use parse to see if the date of birth is correct
from dateutil.parser import parse
Added a function to read #CSV
import pandas as pd
#Create window
root = tk.Tk ()
root.title ("Hello, World!") #Title
root.geometry ("650x300") #size
Number of lines = 3
bt_insert_delete = []
tx_no = []
tx_ surname = []
tx_name = []
tx_gender = []
tx_ date of birth = []
pageid = 0
no = [1,2,3,4,5,6,7,8,9,10,11]
Last name = ["Watanabe", "Yanagawa", "Seino", "Nemoto", "Abe", "Inada", "Kiuchi", "Miyake", "Ishimura", "Hongo", "Yamada"]
Name = ["Saki", "Kazuomi", "Nao", "Shunto", "Ai", "Watoku", "Kio", "Minami", "Hiro", "Kaho", "Hiro"]
Gender = ["Woman", "Men", "Woman", "Men", "Woman", "Men", "Men", "Women", "Men", "Women", "Men"]
Date of Birth = ["1988/07/15", "1966/09/04", "1979/06/08", "1992/03/14", \
           "1977/04/04", "1963/11/06", "1972/08/21", "1992/11/30", \
           "1967/12/07", "1965/03/20", "1977/04/04"]
# ===================================
def screen creation ():
    y = 50
    x = 140
    title = ['No.','Last Name',' First Name',' Gender',' Date of Birth']
    for i in title:
        obj = tk.Label (text = i)
        obj.place (x = x, y = y)
        x + = 80
    y = 80
    for index in range (number of lines):
        x = 140
        obj = tk.Entry (width = 10)
        obj.place (x = x, y = y)
        tx_no.append (obj)
        x + = 80
        obj = tk.Entry (width = 10)
        obj.place (x = x, y = y)
        tx_ surname.append (obj)
        x + = 80
        obj = tk.Entry (width = 10)
        obj.place (x = x, y = y)
        tx_name.append (obj)
        x + = 80
        obj = tk.Entry (width = 10)
        obj.place (x = x, y = y)
        tx_gender.append (obj)
        x + = 80
        obj = tk.Entry (width = 14)obj.place (x = x, y = y)
        tx_ date of birth .append (obj)
        y + = 31
def Delete 1 ():
    print ('Delete 1')
    Delete (0)
def Delete 2 ():
    print ('Delete 2')
    Delete (1)
def Delete 3 ():
    print ('Delete 3')
    Delete (2)

def Delete (index):
    global pageid
    num = pageid
    if (var.get () == True):
        del no [num]
        del surname [num]
        del name [num]
        del Gender [num]
        del date of birth [num]
    else: else:
        no.insert (num,'')
        Last name.insert (num,'')
        First name.insert (num,'')
        Gender.insert (num,'')
        Date of birth. Insert (num,'')
    clear ()
    Screen display()
def screen creation_button ():
    func = [Delete 1, Delete 2, Delete 3]
    y = 78
    for index in range (number of lines):
        x = 50
        obj = tk.Button (width = 10, text ='insert', command = func [index])
        obj.place (x = x, y = y)
        bt_insert_delete.append (obj)
        y + = 30
    Clear_button = tk.Button (root, text ='clear', command = clear)
    Clear_button.place (width = 50, x = 25, y = 250)
    Read_button = tk.Button (root, text ='read', command = btn_read)
    Read_button.place (width = 50, x = 130, y = 250)
    Save_button = tk.Button (root, text ='save', command = btn_save)
    Save_button.place (width = 50, x = 200, y = 250)
    Prev_button = tk.Button (root, text ='previous button', command = previous page)
    Prev_button.place (width = 50, x = 330, y = 250)
    Next_button = tk.Button (root, text ='next button', command = next page)
    Next_button.place (width = 50, x = 400, y = 250)

#Display entry
def screen display ():
    global pageid
    for index in range (number of lines):
        if ((index + pageid)>= len (no)): return
        tx_no [index] .insert (tk.END, no [index + pageid])
        tx_ surname [index] .insert (tk.END, surname [index + pageid])
        tx_name [index] .insert (tk.END, first name [index + pageid])
        tx_ Gender [index] .insert (tk.END, Gender [index + pageid])
        tx_ date of birth [index] .insert (tk.END, date of birth [index + pageid])
def Memory ():
    global pageid
    for index in range (number of lines):
        if not tx_no [index] .get () and not tx_ surname [index] .get () and not tx_ first name [index] .get () and not tx_ gender [index] .get () and not tx_ Date of Birth [index] .get ():
            print ("do not work")
            return
        else: else:for index in range (number of lines):
                if tx_no [index] .get ():
                    no [index + pageid] = tx_no [index] .get ()
                else: else:
                    return
                if tx_ surname [index] .get ():
                    Last name [index + pageid] = tx_ Last name [index] .get ()
                else: else:
                    return
                if tx_name [index] .get ():
                    First name [index + pageid] = tx_ first name [index] .get ()
                else: else:
                    return
                if tx_ gender [index] .get ():
                    Gender [index + pageid] = tx_ Gender [index] .get ()
                else: else:
                    return
                if tx_ date of birth [index] .get ():
                    Date of Birth [index + pageid] = tx_ Date of Birth [index] .get ()
                else: else:
                    return
#def check_content ():
# ===================================
# Erase all entries
def clear ():
    for index in range (number of lines):
        tx_no [index] .delete (0, tk.END)
        tx_ surname [index] .delete (0, tk.END)
        tx_name [index] .delete (0, tk.END)
        tx_ Gender [index] .delete (0, tk.END)
        tx_ date of birth [index] .delete (0, tk.END)
#Read
def btn_read ():
    df = pd.read_csv ('test2.csv', encoding ='shift_jis', header = None)
    no.clear ()
    Last name.clear ()
    First name.clear ()
    Gender.clear ()
    Date of birth. Clear ()
    for i in range (len (df)):
        no.append (str (df.iloc [i, 0]))
        Last name.append (str (df.iloc [i, 1]))
        First name.append (str (df.iloc [i, 2]))
        Gender.append (str (df.iloc [i, 3]))
        Date of birth.append (str (df.iloc [i, 4]))
    clear ()
    index = 0
    Screen display()   
#Save
def btn_save ():
    with open ('test.csv', mode ='w') as file:
        file.write ("No, first name, first name, gender, date of birth \ n")
        for index in range (len (no)):
            s = str (no [index]) + "," + str (last name [index]) + "," + \
            str (name [index]) + "," + str (gender [index]) + "," + str (date of birth [index]) + "\ n"
            file.write (s)
def Previous page ():
    global pageid
    print ("btn_prev: s:", no)
    Memory ()
    if (pageid-3)<0:
        messagebox.showerror ('error','can't go back anymore')
        print ("I can't go back anymore")
        return
    #if check_content ():
        #return
    clear ()pageid-= 3
    Screen display()
    print ("btn_prev: e:", no)
def Next page ():
    global pageid
    print ("btn_next: s:", no)
    print (pageid)
    Memory ()
    #if check_content ():
        #return
    clear ()
    pageid + = 3
    Screen display()
    print ("btn_next: e:", no)
    print (pageid)
def change ():
    for index in range (number of lines):
        if (var.get () == True):
            print ('delete')
            bt_insert_delete [index] .config (text ='delete')
        else: else:
            print ('insert')
            bt_insert_delete [index] .config (text ='insert')
ar = tk.BooleanVar ()
t_btn = tk.Checkbutton (variable = var, text = "insert/delete", command = change)
t_btn.place (x = 40, y = 50)
# ===================================
Screen creation ()
Create screen_button ()
Screen display()    
root.mainloop ()
What I tried

I want to change the memory part and add the desired function, but I can't think of it.

def Memory ():
    global pageid
    for index in range (number of lines):
        if not tx_no [index] .get () and not tx_ surname [index] .get () and not tx_ first name [index] .get () and not tx_ gender [index] .get () and not tx_ Date of Birth [index] .get ():
            print ("do not work")
            return
        else: else:
            for index in range (number of lines):
                if len (no)>= no [index + pageid]
                    no [index + pageid] = tx_no [index] .get ()
                else: else:
                    no [index + pageid] .append (tx_no [index])
            for index in range (number of lines):
                if len (last name)>= last name [index + pageid]
                    Last name [index + pageid] = tx_ Last name [index] .get ()
                else: else:
                    Last name [index + pageid] .append (tx_ last name [index])
            for index in range (number of lines):
                if len (first name)>= first name [index + pageid]
                    First name [index + pageid] = tx_ first name [index] .get ()
                else: else:
                    First name [index + pageid] .append (tx_name [index])
            for index in range (number of lines):
                if len (gender)>= gender [index + pageid]
                    Gender [index + pageid] = tx_ Gender [index] .get ()
                else: else:
                    Gender [index + pageid] .append (tx_gender [index])
            for index in range (number of lines):
                if len (date of birth)>= date of birth [index + pageid]
                    Date of Birth [index + pageid] = tx_ Date of Birth [index] .get ()
                else: else:
                    Date of Birth [index + pageid] .append (tx_ Date of Birth [index])
  • Answer # 1

    When it comes to modifying the Memory function on request, it looks like this.

    def Memory ():
        global pageid
        for index in range (number of lines):
            if not tx_no [index] .get () and not tx_ surname [index] .get () and not tx_ first name [index] .get () and not tx_ gender [index] .get () and not tx_ Date of Birth [index] .get ():
                print ("do not work")
            else: else:
                for i in range (len (no), index + pageid + 1):
                    no.append ('')
                    Last name.append ('')
                    First name.append ('')
                    Gender.append ('')
                    Date of birth.append ('')
                no [index + pageid] = tx_no [index] .get ()
                Last name [index + pageid] = tx_ Last name [index] .get ()
                First name [index + pageid] = tx_ first name [index] .get ()
                Gender [index + pageid] = tx_ Gender [index] .get ()
                Date of Birth [index + pageid] = tx_ Date of Birth [index] .get ()


    First of all, all the Entry widgets have not been entered and have returned.
    Since there are three lines, all the first lines have not been entered as it is,
    Any additions or corrections on the second and subsequent lines will be ignored.

    Also, if there is an input in the Entry widget that is larger than the list,
    We are dealing with it by adding an empty string element up to that size.

  • Answer # 2

    The Japanese code is difficult to read, so I recreated it from scratch.
    (Sorry for the class format.)

    The data is in dictionary format, and the Entry widget is also managed in a list, so I think it is easy to apply in various ways.
    Also saves data when switching pages
    Get Entry at the time of transition → Update dictionary → Delete contents of Entry → Display next page data from dictionary
    It is reproduced in the form of.

    import os
    import csv
    import pandas as pd
    import tkinter as tk
    from tkinter import messagebox
    from tkinter import file dialog
    class MainWindow (tk.Frame):
        def __init __ (self, master):
            super () .__ init __ (master)
            self.master.title ('Hello, World!')
            self.master.geometry ('650x300')
            # Various predefined
            self.data_dic = {'No': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'],
                            'Last name': ['Watanabe','Yanagawa','Seino','Nemoto',' Abe',' Inada',' Kiuchi',' Miyake',' Ishimura',' Hongo',' Yamada'],
                            'Name': ['Saki','Kazuomi','Nao','Shunto','Ai','Watoku','Kio','Minami','Hiro','Kaho','Hiro' ],,
                            'Gender': ['Woman',' Man',' Woman',' Man',' Woman',' Man',' Man',' Woman',' Man',' Woman',' Man'],
                            'Date of Birth': ['1988/07/15', '1966/09/04', '1979/06/08', '1992/03/14', '1977/04/04',
                                        '1963/11/06', '1972/08/21', '1992/11/30', '1967/12/07', '1965/03/20', '1977/04/04']
                            }
            self.colum = 3
            self.title = [key for key in self.data_dic.keys ()]
            self.tx_data = [list () for i in range (len (self.title))]
            self.InsertAndRemoveStatus = []
            self.pageid = 0
            # Various widget generation
            self.CreateWidget ()
        ##### Generating the main widget
        def CreateWidget (self):
            ################################
            Generation of # Label and Entryy = 50
            x = 140
            for i in self.title:
                tk.Label (self.master, text = i) .place (x = x, y = y)
                x + = 80
            y = 80
            for i in range (self.colum):
                x = 140
                for e, box in enumerate (self.tx_data):
                    width = 10
                    if e == 4:
                        width = 14
                    obj = tk.Entry (self.master, width = width)
                    obj.place (x = x, y = y)
                    box.append (obj)
                    x + = 80
                y + = 31
            ################################
            #Insert dictionary data into Entry
            for (key, value), box in zip (self.data_dic.items (), self.tx_data):
                for data, widget in zip (value, box):
                    widget.insert (tk.END, data)
            ################################
            #Button related generation
            self.var = tk.BooleanVar ()
            tk.Checkbutton (variable = self.var, text = "insert/delete", command = self.LabelChange) .place (x = 40, y = 50)
            x = 50
            y = 78
            for i in range (self.colum):
                obj = tk.Button (self.master, width = 10, text ='insert')
                obj.place (x = x, y = y)
                self.InsertAndRemoveStatus.append (obj)
                y + = 30
            button_data = {'Clear': [25, self.FieldClear],
     'Read': [130, self.DataRead],
     'Save': [200, self.DataSave],
                            'Previous button': [330, self.PreviousPage],
     'Next Button': [400, self.NextPage]}
            for key, value in button_data.items ():
                tk.Button (self.master, text = key, command = value [1]). place (width = 50, x = value [0],
     y = 250)
        ##### Button Event
        def LabelChange (self):
            # Instead of looping by the number of lines, it can be simplified by updating directly from the list that stores the button.
            if self.var.get ():
                [label.configure (text ='remove') for label in self.InsertAndRemoveStatus]
            else: else:
                [label.configure (text ='insert') for label in self.InsertAndRemoveStatus]
        def NextPage (self):
            self.TemporaryMemory ()
            self.FieldClear ()
            self.pageid + = 1
            self.EntryLoading ()
        def PreviousPage (self):
            # Measure the boolean value and if the page id is 0, interrupt the process + error message
            if self.pageid == 0:
                messagebox.showerror ('error','can't go back anymore')
                return
            self.TemporaryMemory ()
            self.FieldClear ()
            self.pageid-= 1self.EntryLoading ()
        def EntryLoading (self):
            for (key, value), box in zip (self.data_dic.items (), self.tx_data):
                for widget, data in zip (box, value [self.pageid * self.colum: self.pageid * self.colum + self.colum]):
                    widget.insert (tk.END, data)
        def DataRead (self):
            fTyp = [('','. Csv')]
            iDir = os.path.abspath (os.path.dirname (__ file__))
            file_name = filedialog.askopenfilename (filetypes = fTyp, initialdir = iDir)
            #Measure the boolean value and if it is True, read it and rewrite the contents of self.data_dic
            #Reset pageid as well
            if file_name:
                self.pageid = 0
                df = pd.read_csv (file_name, encoding ='shift_jis', header = None)
                df = df.fillna ('')
                self.FieldClear ()
                for i in df:
                    dic = {}
                    tmp = []
                    for e, data in enumerate (df [i]):
                        if e == 0:
                            header = data
                        else: else:
                            tmp.append (data)
                    self.data_dic [header] = tmp
                for (key, value), box in zip (self.data_dic.items (), self.tx_data):
                    for data, widget in zip (value, box):
                        widget.insert (tk.END, data)
        def DataSave (self):
            fTyp = [('','. Csv')]
            iDir = os.path.abspath (os.path.dirname (__ file__))
            file_name = filedialog.asksaveasfilename (filetypes = fTyp, initialdir = iDir)
            # Complement the extension when the extension is not entered when saving
            if'.csv' not in file_name:
                file_name = file_name +'.csv'
            #Measure the boolean value, write processing if True, specify line break at the end of line with linetarminator using csv.writer
            if file_name:
                self.TemporaryMemory ()
                with open (file_name, mode ='w') as csvfile:
                    writer = csv.writer (csvfile, lineterminator ='\ n')
                    writer.writerow ([key for key in self.data_dic.keys ()])
                    for index in range (len (self.data_dic ['No'])):
                        word = []
                        for values ​​in self.data_dic.values ​​():
                            word.append (values ​​[index])
                        writer.writerow (word)
                messagebox.showinfo ('written complete', f'saved to {file_name}')
        def Field Clear (self):
            # Erase all entered strings in the Entry widget
            for box in self.tx_data:
                for data in box:
                    data.delete (0, tk.END)
        def TemporaryMemory (self):
            keys = [key for key in self.data_dic.keys ()]
            for e, box in enumerate (self.tx_data):
                for n, widget in enumerate (box):
                    data = widget.get ()
                    try: try:
                        self.data_dic [keys [e]] [n + self.pageid * self.colum] = data
                    except:
                        pass
    if __name__ =='__main__':
        root = tk.Tk ()
        window = MainWindow (master = root)
        window.mainloop ()

Related articles