2021年2月11日星期四

Fixing problems in an appointment module in calendar format

I am working on a module which is a an appointment module in a calendar format. Now there is a problem that I tried to solve but failed in doing so. The problem regarding the module is:-

  1. Making the calendar appointment recent. ( for example, if todays date is 11/2/2021 then any appointment that is done today and set on any date before 11/2/2021 should be cancelled)

I will be adding the whole code for my module reference

Small notice: I am still a beginner in programming so pls take me easy because I am still learning and this module is a practice given by my institution.

thank you

Code ( actually its three files)

File 1 - Calendar.py

import calendar  import datetime  import sys    # imports correct version of tkinter based on python version  if sys.version[0] == '2':      import Tkinter as tk  else:      import tkinter as tk      class Calendar:      # Instantiation      def __init__(self, parent, values):          self.values = values          self.parent = parent          self.cal = calendar.TextCalendar(calendar.SUNDAY)          self.year = datetime.date.today().year          self.month = datetime.date.today().month          self.wid = []          self.day_selected = 1          self.month_selected = self.month          self.year_selected = self.year          self.day_name = ''          self.COLOR_OF_CALENDAR_ARROWS = "lightblue"          self.COLOR_OF_CALENDAR_LABEL = "lightblue"          self.COLOR_OF_DAY_BUTTONS = "lightblue"            self.setup(self.year, self.month)        # Resets the buttons      def clear(self):          for w in self.wid[:]:              w.grid_forget()              # w.destroy()              self.wid.remove(w)        # Moves to previous month/year on calendar      def go_prev(self):          if self.month > 1:              self.month -= 1          else:              self.month = 12              self.year -= 1          # self.selected = (self.month, self.year)          self.clear()          self.setup(self.year, self.month)        # Moves to next month/year on calendar      def go_next(self):          if self.month < 12:              self.month += 1          else:              self.month = 1              self.year += 1            # self.selected = (self.month, self.year)          self.clear()          self.setup(self.year, self.month)        # Called on date button press      def selection(self, day, name):          self.day_selected = day          self.month_selected = self.month          self.year_selected = self.year          self.day_name = name            # Obtaining data          self.values['day_selected'] = day          self.values['month_selected'] = self.month          self.values['year_selected'] = self.year          self.values['day_name'] = name          self.values['month_name'] = calendar.month_name[self.month_selected]            self.clear()          self.setup(self.year, self.month)        def setup(self, y, m):          # Tkinter creation          left = tk.Button(self.parent, text='<', command=self.go_prev, bg=self.COLOR_OF_CALENDAR_ARROWS)          self.wid.append(left)          left.grid(row=0, column=1)            header = tk.Label(self.parent, height=2, bg=self.COLOR_OF_CALENDAR_LABEL,                            text='{}   {}'.format(calendar.month_abbr[m], str(y)))          self.wid.append(header)          header.grid(row=0, column=2, columnspan=3)            right = tk.Button(self.parent, text='>', command=self.go_next, bg=self.COLOR_OF_CALENDAR_ARROWS)          self.wid.append(right)          right.grid(row=0, column=5)            days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']          for num, name in enumerate(days):              t = tk.Label(self.parent, text=name[:3], bg=self.COLOR_OF_CALENDAR_LABEL)              self.wid.append(t)              t.grid(row=1, column=num)            for w, week in enumerate(self.cal.monthdayscalendar(y, m), 2):              for d, day in enumerate(week):                  if day:                      b = tk.Button(self.parent, width=1, bg=self.COLOR_OF_DAY_BUTTONS, text=day,                                    command=lambda day=day: self.selection(day, calendar.day_name[(day) % 7]))                      self.wid.append(b)                      b.grid(row=w, column=d)            sel = tk.Label(self.parent, height=2, bg=self.COLOR_OF_CALENDAR_LABEL, text='{} {} {} {}'.format(              self.day_name, calendar.month_name[self.month_selected], self.day_selected, self.year_selected))          self.wid.append(sel)          sel.grid(row=8, column=0, columnspan=7)        # Quit out of the calendar and terminate tkinter instance.      def kill_and_save(self):          self.parent.destroy()  

File 2 - CalendarView.py

import calendar  import datetime  import sys  import csv    # imports correct version of tkinter based on python version  if sys.version[0] == '2':      import Tkinter as tk  else:      import tkinter as tk      class CalendarView:      # Instantiation      def __init__(self, parent, values):          self.values = values          self.parent = parent          self.cal = calendar.TextCalendar(calendar.SUNDAY)          self.year = datetime.date.today().year          self.month = datetime.date.today().month          self.wid = []          self.day_selected = 1          self.month_selected = self.month          self.year_selected = self.year          self.day_name = ''          self.COLOR_OF_CALENDAR_ARROWS = "lightblue"          self.COLOR_OF_CALENDAR_LABEL = "lightblue"          self.COLOR_OF_DAY_BUTTONS = "lightblue"          self.COLOR_OF_APP_DAY_BUTTONS = "red"            self.setup(self.year, self.month)        # Resets the buttons      def clear(self):          for w in self.wid[:]:              w.grid_forget()              # w.destroy()              self.wid.remove(w)        # Moves to previous month/year on calendar      def go_prev(self):          if self.month > 1:              self.month -= 1          else:              self.month = 12              self.year -= 1          # self.selected = (self.month, self.year)          self.clear()          self.setup(self.year, self.month)        # Moves to next month/year on calendar      def go_next(self):          if self.month < 12:              self.month += 1          else:              self.month = 1              self.year += 1            # self.selected = (self.month, self.year)          self.clear()          self.setup(self.year, self.month)        # Called on date button press      def selection(self, day, name):          # Code goes here when user selects a day button.          pass        def setup(self, y, m):          # Tkinter creation          left = tk.Button(self.parent, text='<', command=self.go_prev, bg=self.COLOR_OF_CALENDAR_ARROWS)          self.wid.append(left)          left.grid(row=0, column=1)            header = tk.Label(self.parent, height=2, bg=self.COLOR_OF_CALENDAR_LABEL,                            text='{}   {}'.format(calendar.month_abbr[m], str(y)))          self.wid.append(header)          header.grid(row=0, column=2, columnspan=3)            right = tk.Button(self.parent, text='>', command=self.go_next, bg=self.COLOR_OF_CALENDAR_ARROWS)          self.wid.append(right)          right.grid(row=0, column=5)            days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']          for num, name in enumerate(days):              t = tk.Label(self.parent, text=name[:3], bg=self.COLOR_OF_CALENDAR_LABEL)              self.wid.append(t)              t.grid(row=1, column=num)          # Read Appointments          appointments = []          bookedDays = []          with open("appointments.txt", 'r') as appFile:              reader = csv.reader(appFile)              for row in reader:                  # removes empty list from loop                  if len(row) > 0:                      # Check for appointments made by this user                      if row[0] in self.values:                          # Parse the date into day,month,year                          dayInt, monthInt, yearInt = row[1].split("/")                          appointments.append((int(dayInt), int(monthInt), int(yearInt)))            print("appointments:" + str(appointments))          for w, week in enumerate(self.cal.monthdayscalendar(y, m), 2):              for d, day in enumerate(week):                  if day:                      # determine the color of current calendar day                      color = self.COLOR_OF_APP_DAY_BUTTONS if (day, m, y) in appointments else self.COLOR_OF_DAY_BUTTONS                      btn = tk.Button(self.parent, text=day, bg=color,                                      command=lambda day=day: self.selection(day, calendar.day_name[day % 7]))                      btn.grid(row=w, column=d, sticky='nsew')        # Quit out of the calendar and terminate tkinter instance.      def kill_and_save(self):          self.parent.destroy()  

File 3 - SwimSchool.py

import tkinter as tk  import csv  import sys  import os.path  from tkinter import messagebox  from PIL import Image,ImageTk  from Calendar import Calendar  from CalendarView import CalendarView    root = tk.Tk()  root.title("Medical centre appointment")  #Tikinter Vars  username = tk.StringVar()  password = tk.StringVar()  name = tk.StringVar()  loggedInLabel = tk.StringVar()  hours = tk.IntVar()  minutes = tk.IntVar()  #Functions  def setup():      #Used to make the two textfiles if they don't already exist      file_exists = os.path.isfile("users.txt")      if file_exists:          pass      else:          file = open("users.txt", "w+")          file.close()      file_exists = os.path.isfile("appointments.txt")      if file_exists:          pass      else:          file = open("appointments.txt", "w+")          file.close()  def raiseFrame(frame):      frame.tkraise()  def moveToReg():      raiseFrame(regFrame)  def moveToLogin():      raiseFrame(start)  def moveToBook():      raiseFrame(bookAppointment)      # Calendar  def moveToUser():      raiseFrame(userFrame)  def register():      entries = []      with open ("users.txt",'a',newline="") as userFile:          writer = csv.writer(userFile)          writeList = [name.get(),username.get(),password.get()]          writer.writerow(writeList)          userFile.close()      #Clear entry boxes      username.set("")      password.set("")      raiseFrame(start)        def makeAppointment(calendarViewFrame):      #Format date      date = str(datePickercalendar.day_selected)+"/"+str(datePickercalendar.month_selected)+"/"+str(datePickercalendar.year_selected)      #Format time      minutesString=str(minutes.get())      if minutes.get()==0:          minutesString = "00"      time = str(hours.get())+":"+minutesString      with open ("appointments.txt",'a',newline="") as appFile:          writer = csv.writer(appFile)          writeList = [name.get(),date,time]          writer.writerow(writeList)          appFile.close()      messagebox.showinfo("Success!","Appointment made!")      calendarViewFrame = tk.Frame(userFrame, borderwidth=5, bg="lightblue")      calendarViewFrame.grid(row=2, column=1, columnspan=5)      viewCalendar = CalendarView(calendarViewFrame, {name.get()})      raiseFrame(userFrame)        def login():      with open("users.txt",'r') as userFile:          reader = csv.reader(userFile)          for row in reader:              #removes empty list from loop              if len(row)>0:                  if username.get()==row[1] and password.get()==row[2]:                      print(row[0]+" has logged in!")                      #Set welcome message                      loggedInLabel.set("Welcome, "+row[0])                      # Calendar View                      global calendarViewFrame                      calendarViewFrame = tk.Frame(userFrame, borderwidth=5, bg="lightblue")                      calendarViewFrame.grid(row=2, column=1, columnspan=5)                      viewCalendar = CalendarView(calendarViewFrame, {row[0]})                      name.set(row[0])                      raiseFrame(userFrame)                        def logOut():      #Clear Entry boxes      name.set("")      username.set("")      password.set("")      raiseFrame(start)  #Call setup  setup()  #Define Frame  start = tk.Frame(root)  regFrame = tk.Frame(root)  userFrame = tk.Frame(root)  bookAppointment = tk.Frame(root)  frameList=[start,regFrame,userFrame,bookAppointment]  #Configure all (main) Frames  for frame in frameList:      frame.grid(row=0,column=0, sticky='news')      frame.configure(bg='lightblue')        #Define Image  swimimage=Image.open("swimmerIcon.png")  swimimagePH=ImageTk.PhotoImage(swimimage)  #Labels  tk.Label(start,text="Medical centre appointment",font=("Courier", 60),bg='lightblue').grid(row=0,column=1,columnspan=5)  tk.Label(start,image=swimimagePH,bg='lightblue').grid(row=1,column=1,columnspan=5)  tk.Label(start,text="Username: ",font=("Courier", 22),bg='lightblue').grid(row=2,column=1)  tk.Label(start,text="Password: ",font=("Courier", 22),bg='lightblue').grid(row=3,column=1)    tk.Label(regFrame,text="Register",font=("Courier", 44),bg='lightblue').grid(row=1,column=1,columnspan=5)  tk.Label(regFrame,text="Name: ",font=("Courier", 22),bg='lightblue').grid(row=2,column=1)  tk.Label(regFrame,text="Username: ",font=("Courier", 22),bg='lightblue').grid(row=3,column=1)  tk.Label(regFrame,text="Password: ",font=("Courier", 22),bg='lightblue').grid(row=4,column=1)    tk.Label(userFrame,textvariable = loggedInLabel,font=("Courier", 44),bg='lightblue',fg="blue").grid(row=1,column=1,columnspan=5)    tk.Label(bookAppointment,text="Book an Appointment",font=("Courier", 44),bg='lightblue').grid(row=1,column=1,columnspan=5)  tk.Label(bookAppointment,text="Select a Date: ",font=("Courier", 22),bg='lightblue').grid(row=2,column=1)  tk.Label(bookAppointment,text="Select a Time: ",font=("Courier", 22),bg='lightblue').grid(row=3,column=1)  #Entry Boxes  tk.Entry(start,textvariable=username,font=("Courier", 22),bg='lightblue').grid(row=2,column=2)  tk.Entry(start,textvariable=password,font=("Courier", 22),bg='lightblue').grid(row=3,column=2)    tk.Entry(regFrame,textvariable=name,font=("Courier", 22),bg='lightblue').grid(row=2,column=2)  tk.Entry(regFrame,textvariable=username,font=("Courier", 22),bg='lightblue').grid(row=3,column=2)  tk.Entry(regFrame,textvariable=password,font=("Courier", 22),bg='lightblue').grid(row=4,column=2)  #Buttons  tk.Button(start,font=("Courier", 22),bg='cyan',text="Login",command=login).grid(row=4,column=2)  tk.Button(start,font=("Courier", 22),bg='cyan',text="Register",command=moveToReg).grid(row=4,column=1)    tk.Button(regFrame,font=("Courier", 22),bg='cyan',text="Register",command=register).grid(row=5,column=2)  tk.Button(regFrame,font=("Courier", 22),bg='cyan',text="Back",command=moveToLogin).grid(row=5,column=1)    tk.Button(userFrame,font=("Courier", 22),bg='cyan',text="Log Out",command=logOut).grid(row=3,column=1)  tk.Button(userFrame,font=("Courier", 22),bg='cyan',text="Book Appointment",command=moveToBook).grid(row=3,column=2)    tk.Button(bookAppointment,font=("Courier", 22),bg='cyan',text="Make Appointment",command=lambda :makeAppointment(calendarViewFrame)).grid(row=5,column=2)  tk.Button(bookAppointment,font=("Courier", 22),bg='cyan',text="Back",command=moveToUser).grid(row=5,column=1)      #Time Selector  timeSelectFrame = tk.Frame(bookAppointment,borderwidth=5,bg="lightblue")  timeSelectFrame.grid(row=3,column=2)  tk.Spinbox(timeSelectFrame,from_=1, to=24,bg="lightblue",width=2,textvariable=hours).grid(row=1,column=1)  tk.Label(timeSelectFrame,text=":",bg="lightblue").grid(row=1,column=2)  tk.Spinbox(timeSelectFrame,width=2,textvariable=minutes,values=(0,15,30,45),bg="lightblue").grid(row=1,column=3)    calendarFrame = tk.Frame(bookAppointment, borderwidth=5, bg="lightblue")  calendarFrame.grid(row=2, column=2, columnspan=5)  datePickercalendar = Calendar(calendarFrame, {})  #Raise Initial Frame  raiseFrame(start)  root.mainloop()  
https://stackoverflow.com/questions/66150461/fixing-problems-in-an-appointment-module-in-calendar-format February 11, 2021 at 03:30PM

没有评论:

发表评论