简体   繁体   中英

How to save tkcalendar in textfile

I hope someone can help me and I'll really appreciate it. I'm really having a hard time with saving this Calendar input in the Textfile after showing the date in the Treeview. By the way, here's my import: from tkcalendar import DateEntry

This is what I'm doing: Picking a date in the Calendar. After picking the date, it will show up on my Treeview. After that, I want to save the date I picked from Treeview to Textfile.

Here's my full code:

from tkinter import *
from PIL import Image, ImageTk
import tkinter as tk
import tkinter.ttk as ttk
from tkcalendar import DateEntry

IMAGE_PATH = 'latestBG.gif'
WIDTH, HEIGHT = 1400, 1000

root = tk.Tk()
root.title("Case Study")
root.geometry('{}x{}'.format(WIDTH, HEIGHT))
root.geometry('1400x1300')
frame = tk.Frame(root)

img = ImageTk.PhotoImage(Image.open(IMAGE_PATH).resize((WIDTH, HEIGHT)))
lbl = tk.Label(root, image=img)
lbl.img = img
lbl.place(relx=0.5, rely=0.5, anchor='center')

data2 = []


def loaddata2():
    for item in recordTable2.get_children():
        recordTable2.delete(item)
    for r in range(len(data2)):
        recordTable2.insert(parent='', index='end', text='', values=data2[r], iid=r)


def addRecords2(Fullname2, Number2, Date2, Time2):
    data2.append([Fullname2, Number2, Date2, Time2])

    loaddata2()


Fullname = StringVar()
Number = StringVar()
Date = StringVar()
Time = StringVar()

def savefile2():
    fname = Fullname.get()
    number = Number.get()
    date = Date.get()
    time = Time.get()

    print(fname, number, date, time)

    file = open('appointment1.txt', 'a')
    file.write("=============================================================\n")
    file.write("                     APPOINTMENT RECORDS\n")
    file.write("=============================================================\n")
    file.write('\t' + "     Full Name: " + fname + '\n')
    file.write('\t' + "     Number: " + number + '\n')
    file.write('\t' + "     Date: " + date + '\n')
    file.write('\t' + "     Time: " + time + '\n')
    file.write("=============================================================")
    file.write("\n\n")
    file.close()

def upRecords2(Fullname2, Number2, Date2, Time2, index2):
    data2[index2] = [Fullname2, Number2, Date2, Time2]

    loaddata2()


def putdata_inEntry2(index2):
    fullname1Entry.delete(0, tk.END)
    number1Entry.delete(0, tk.END)
    date1Entry.delete(0, tk.END)
    time1Entry.delete(0, tk.END)

    Fullname2 = data2[index2][0]
    Number2 = data2[index2][1]
    Date2 = data2[index2][2]
    Time2 = data2[index2][3]


    fullname1Entry.insert(0, Fullname2)
    number1Entry.insert(0, Number2)
    date1Entry.insert(0, Date2)
    time1Entry.insert(0, Time2)

def deldata2(index2):

    del data2[index2]
    loaddata2()

def cleardata2():

    fullname1Entry.delete(0, tk.END)
    number1Entry.delete(0, tk.END)
    date1Entry.delete(0, tk.END)
    time1Entry.delete(0, tk.END)


def searchdata2(Fullname1):
    if Fullname1 != '':
        data_index = []

        for info in data2:
            if str(Fullname1) in str(info[0]):
                data_index.append(data2.index(info))

        for item in recordTable2.get_children():
            recordTable2.delete(item)
        for r in data_index:
            recordTable2.insert(parent='', index='end', text='', values=data2[r], iid=r)

    else:
        loaddata2()


heading2 = tk.Label(root, text='APPOINTMENT', font=('Bold', 14), bg='black', foreground='white', width=25)
heading2.place(x=920, y=250)

Fullname1 = tk.Label(root, text="FULL NAME", font=('Bold', 13))
Fullname1.place(x=920, y=300)
fullname1Entry = tk.Entry(root, textvariable=Fullname, font=('Bold', 13))
fullname1Entry.place(x=1020, y=300, width=180)

number1 = tk.Label(root, text="NUMBER", font=('Bold', 13))
number1.place(x=920, y=330)
number1Entry = tk.Entry(root, textvariable=Number, font=('Bold', 13))
number1Entry.place(x=1020, y=330, width=180)

date1 = tk.Label(root, text="DATE", font=('Bold', 13))
date1.place(x=920, y=360)
date1Entry = DateEntry(root, selectmode='day')
date1Entry.place(x=1020, y=360, width=180)

time1 = tk.Label(root, text="TIME", font=('Bold', 13))
time1.place(x=920, y=390)
time1Entry = tk.Entry(root, textvariable=Time, font=('Bold', 13))
time1Entry.place(x=1020, y=390, width=180)

regbutton2 = tk.Button(root, text="ADD DATA", font=('Bold', 11), command=lambda: [addRecords2(fullname1Entry.get(), number1Entry.get(), date1Entry.get(), time1Entry.get()), savefile2()])
regbutton2.place(x=895, y=470)


upbutton2 = tk.Button(root, text="UPDATE DATA", font=('Bold', 11),
                     command=lambda: upRecords2(fullname1Entry.get(), number1Entry.get(), date1Entry.get(), time1Entry.get(),
                                               index2=int(recordTable2.selection()[0])))
upbutton2.place(x=990, y=470)

delbutton2 = tk.Button(root, text="DELETE DATA", font=('Bold', 11), command=lambda: deldata2(index2=int(recordTable2.selection()[0])))
delbutton2.place(x=1110, y=470)

clearbutton2 = tk.Button(root, text="CLEAR DATA", font=('Bold', 11), command=lambda: cleardata2())
clearbutton2.place(x=1230, y=470)

frame.pack(pady=10)
frame.pack_propagate(False)
frame.configure(width=300, height=30, bg='black')
frame.place(x=200, y=250)

search_bar_frame2 = tk.Frame(root)

searchlbl2 = tk.Label(search_bar_frame2, text='Search Appointment by Name:', font=('Bold', 12))
searchlbl2.pack(anchor=tk.S)

searchEntry2 = tk.Entry(search_bar_frame2, font=('Bold', 12))
searchEntry2.pack(anchor=tk.S)
searchEntry2.bind('<KeyRelease>', lambda e: searchdata2(searchEntry2.get()))

search_bar_frame2.pack(pady=0)
search_bar_frame2.pack_propagate(False)
search_bar_frame2.configure(width=300, height=60)
search_bar_frame2.place(x=920, y=510)


recordFrame2 = tk.Frame(root)

recordTable2 = ttk.Treeview(recordFrame2)
recordTable2.pack(fill=tk.X, pady=5)
recordTable2.bind('<<TreeviewSelect>>', lambda e: putdata_inEntry2(int(recordTable2.selection()[0])))

recordTable2['column'] = ['FullName', 'Number', 'Date', 'Time']
recordTable2.column('#0', anchor=tk.W, width=0, stretch=tk.NO)

recordTable2.column('FullName', anchor=tk.W, width=50)
recordTable2.column('Number', anchor=tk.W, width=50)
recordTable2.column('Date', anchor=tk.W, width=50)
recordTable2.column('Time', anchor=tk.W, width=50)

recordTable2.heading('FullName', text='Full Name', anchor=tk.W)
recordTable2.heading('Number', text='Number', anchor=tk.W)
recordTable2.heading('Date', text='Date', anchor=tk.W)
recordTable2.heading('Time', text='Time', anchor=tk.W)

recordFrame2.pack(fill=tk.X)
recordFrame2.pack(pady=10)
recordFrame2.pack_propagate(False)
recordFrame2.configure(width=500, height=200)
recordFrame2.place(x=830, y=580)


loaddata2()

root.mainloop()

Some time ago I created a calendar/to-do list where I had to do just that and I had the same problem.

I solved it in a way that may not be the prettiest but it works correctly.

This is the link to the GitHub repository of the project I'm talking about: https://github.com/FranGarcia94/ToDo-list-Calendar

First you have to create a text file .txt where you want to save the information, in my case I needed to write and read information so first, if it is not created, it is created and if it is already created, it is read.

def load_task():
    
    # Create the .txt file if it doesn't exist
    with open('C:\\Users\\...\\saved_events.txt', 'a+') as f:

        f.close()

    with open('C:\\Users\\...\\saved_events.txt', 'r') as f:

        txt_reader = f.readlines()
        txt_reader = [txt_reader[i].split('\n') for i in range(len(txt_reader))]
        [txt_reader[i].remove('') for i in range(len(txt_reader)) if len(txt_reader[i]) > 1]

If you take a look at the repository you will see that there is more code below these lines. This is to highlight in the calendar the days in which there are tasks and to read correctly the dates since as I have told you I put them in a special way.

In my case, I divided my txt file into two parts, the upper part would store the tasks and the lower part would store the dates, separated by a line break.

在此处输入图像描述

I didn't use Treeview but that doesn't matter, you just have to be clear about what you want to save and how and create a separate list and this way you can save the data in a text file.

with open('C:\\Users\\...\\saved_events.txt', 'w') as f:

    for i in tag_list:

        f.write(f'{i}\n')
    
    f.write('\n')

    for i in date_list:

        f.write(f'{i}\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM