0

I wanted to create a date-picker but it does not work at all, instead, irrespective of the date i pick on the following menu:

The Calendar I made

It just outputs the current date:

The Output it gives every time is the current date

The second I click on the button that is calling the function dispcal(), the IDLE prints out the current date automatically, I don't know why. And when I click on the button Get This Date, and it calls the function getCustomDate(), it just doesn't do what it's supposed to do, and does not print anything.

Here is the code of the date picker and calendar function:

def getCustomDate():
    print(cal.get_date())
def dispcal():
    global cal
    calFrame=LabelFrame(mainL,borderwidth=0, bg="#c3dde6", height=100, width=100)
    calFrame.grid(row=1, column=0, sticky=NSEW)
    cal=Calendar(calFrame, selectmode="day",firstweekday="monday",background="#0f8bff",foreground="black",disabledforeground="#a3bec7",bordercolor="grey",normalbackground="#d0f4ff",weekendbackground="#8ffeff",weekendforeground ="black" ,disabledbackground="99b3bc",year=int(datetime.datetime.now().strftime("%Y")),month=int(datetime.datetime.now().strftime("%m")), day=int(datetime.datetime.now().strftime("%d")))
    cal.pack(pady=10)
    getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())
    getdat.pack()

Updates

Thanks to @j_4321 for solving my problem, I created a fresh python file and ran the code in that, the one with the custom format I want for my Calendar Date Picker and it works like a charm and gives the desired output.

fresh.py:

from tkinter import *
from tkcalendar import *
root=Tk()
root.geometry("500x500")
def mainF():
    global cal
    def getDate():
        date=cal.get_date()
        print(date)
    cal.pack(pady=20, padx=20)
    butt=Button(root,text="Date Getter", bg="cyan",command=getDate).pack()
cal=Calendar(root,selectmode="day",date_pattern="dd-mm-y")
but=Button(root,text="Pick Date",command=mainF).pack()
root.mainloop()

Code working Properly

However in my main.py, the same code just does not work and gives the following error message:

<bound method Calendar.get_date of <tkcalendar.calendar_.Calendar object .!labelframe.!frame2.!frame.!frame2.!calendar>>

I don't know why this is happening, maybe there is a problem in my main.py code but I just can't seem to find it out.

Here is my main.py code:

from calendar import firstweekday
import csv, datetime
from tkinter import *
from tkcalendar import *
from tkinter import ttk
from PIL import Image, ImageTk
now=datetime.datetime.now().strftime("%d-%m-%Y")

f=open("Dr Nikhil Prescription App\Patient_Data.csv","r", newline="")
reader=csv.reader(f, delimiter=",")
L=[k[0] for k in reader]
try:
    sndat=str(1+(int(L[-1])))
except ValueError:
    sndat=1
f.close()

from tkinter import messagebox
def DataAdder2CSV():
    global edate, eSNO, eage, egender, ename, ePID, econtact, ecomp, eallergy, ehistory, eR
    e=edate.get()
    a=eSNO.get()
    d=eage.get()
    f=egender.get()
    b=ename.get()
    c=ePID.get()
    g=econtact.get()
    h=ecomp.get(1.0,END)
    i=eallergy.get(1.0,END)
    j=ehistory.get(1.0,END)
    k=eR.get(1.0,END)
    data=[a,b,c,d,e,f,g,h,i,j,k]
        
    file=open("Patient_Data.csv","a", newline="")
    writer=csv.writer(file, delimiter=",")

    writer.writerow(data)

    file.close()
    messagebox.showinfo("Prescription Generator", "Data has been saved to the database successfully!")    
def PrescGen():
    from tkinter import filedialog
    root.filename=filedialog.askdirectory(initialdir="Documents", title="Choose Destination Folder")
    '''
    import win32com.client, os
    psApp = win32com.client.Dispatch("Photoshop.Application")
    psApp.Open("Presc_Template.psd")
    doc = psApp.Application.ActiveDocument
    layer_facts = doc.ArtLayers["GLAYER"]
    text_of_layer = layer_facts.TextItem
    text_of_layer.contents = "This is an example of a new text."
    '''
    messagebox.showinfo("Prescription Generator", "Prescription has been saved in the desired location successfully!")  
def dispcal():

    calFrame.grid(row=1, column=0,pady=60, sticky=NSEW)
    cal.pack(pady=10,padx=50, fill="both", expand=True)

    def getCustomDate():
        print(cal.get_date)
    getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate)
    getdat.pack()

root=Tk()
root.config(bg="#add8e6")

megaF=LabelFrame(root,bg="#add8e6", borderwidth=0)
megaF.pack()

greet=Label(megaF,font="Arial 25",text="Prescription Generator", bg="#add8e6", fg="black").pack(pady=20)

dateF=Frame(megaF, padx=10, pady=10, bg="#c3dde6")
dateF.pack()

mega2F=Frame(megaF,bg="#c3dde6")
mega2F.pack()

date=Label(dateF,font="Arial 12",text="Date:", bg="#c3dde6").grid(row=0,column=0)

edate=Entry(dateF, width=10)
edate.insert(0,now)
edate.grid(row=0, column=1, padx=5)

CalIMG=ImageTk.PhotoImage(Image.open("D:\Coding\Python Scripts\Dr Nikhil Prescription App\cal.png"))

mainL=Frame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
mainL.grid(row=0, column=0)

calFrame=Frame(mainL,borderwidth=0, bg="#c3dde6", height=200, width=100)

cal=Calendar(calFrame,
date_pattern="dd-mm-y",
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black" ,
disabledbackground="99b3bc")

CalButt=Button(dateF, image=CalIMG, command=dispcal, borderwidth=0, bg="#c3dde6").grid(row=0, column=2, padx=5)

main2L=LabelFrame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
main2L.grid(row=0, column=1,pady=20, padx=40)

PDlf=Frame(mainL, padx=10, pady=13, bg="#c3dde6")
PDlf.grid(row=0, column=0, sticky=NSEW)

sno=Label(PDlf,font="Arial 14",text="Sno:", bg="#c3dde6").grid(row=0,column=0, sticky=E)
eSNO=Entry(PDlf, width=3)
eSNO.insert(0,sndat)
eSNO.grid(row=0, column=1)

age=Label(PDlf,font="Arial 14",text="Age:", bg="#c3dde6").grid(row=1,column=0, sticky=E)
eage=Entry(PDlf, width=3)
eage.grid(row=1, column=1, pady=10)

gender=Label(PDlf,font="Arial 14",text="Gender:", bg="#c3dde6").grid(row=2,column=0, sticky=E)
egender=Entry(PDlf, width=3)
egender.grid(row=2, column=1)

name=Label(PDlf,font="Arial 14",text="Name:", bg="#c3dde6").grid(row=0,column=3, sticky=E)
ename=Entry(PDlf, width=15)
ename.grid(row=0, column=4)

Pid=Label(PDlf,font="Arial 14",text="PatientID:", bg="#c3dde6").grid(row=1,column=3, sticky=E)
ePID=Entry(PDlf, width=15)
ePID.grid(row=1, column=4, pady=10)

contact=Label(PDlf,font="Arial 14",text="Contact:", bg="#c3dde6").grid(row=2,column=3, sticky=E)
econtact=Entry(PDlf, width=15)
econtact.grid(row=2, column=4)

blank=Label(PDlf,font="Arial 14",text="         ", bg="#c3dde6").grid(row=1,column=2)

contentLF=LabelFrame(main2L, padx=10, pady=10, bg="#c3dde6", borderwidth=0)
contentLF.grid(row=0, column=2, sticky=SE)

blank=Label(PDlf,font="Arial 14",text="         ", bg="#c3dde6").grid(row=0,column=2)

complaint=Label(contentLF,font="Arial 14",text="Complaint:", bg="#c3dde6").grid(row=0,column=1, sticky=E)
ecomp=Text(contentLF, width=90, height=4)
ecomp.grid(row=0, column=2)

allergy=Label(contentLF,font="Arial 14",text="Allergy:", bg="#c3dde6").grid(row=1,column=1, sticky=E)
eallergy=Text(contentLF, width=90, height=2)
eallergy.grid(row=1, column=2, pady=10)

history=Label(contentLF,font="Arial 14",text="History:", bg="#c3dde6").grid(row=2,column=1, sticky=E)
ehistory=Text(contentLF, width=90, height=5)
ehistory.grid(row=2, column=2)

R=Label(contentLF,font="Arial 14",text="Diagnosis:", bg="#c3dde6").grid(row=3,column=1, sticky=E)
eR=Text(contentLF, width=90, height=12)
eR.grid(row=3, column=2, pady=10)

buttF=LabelFrame(main2L, bg="#c3dde6", borderwidth=0)
buttF.grid(row=4, column=2, sticky=E)
genPres=Button(buttF,font="Arial 12",text="Generate Prescription", bg="#ff80b9", command=PrescGen).grid(row=0, column=0, padx=10, sticky=E)

csvAdd=Button(buttF,font="Arial 12",text="Add to Database", bg="#49ff9a", command=DataAdder2CSV).grid(row=0, column=1,padx=10, sticky=E)

root.title("Prescription Generator")
root.state("zoomed")
root.mainloop()
halfer
  • 19,824
  • 17
  • 99
  • 186
Deven Jain
  • 27
  • 1
  • 8
  • 1
    Part of your problem is similar to https://stackoverflow.com/questions/5767228/why-is-the-command-bound-to-a-button-or-event-executed-when-declared. In `getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())` you are executing the function instead of passing it as an argument. – j_4321 May 19 '21 at 07:38
  • 1
    Secondly, you are not specifying the date format you want to use, so `tkcalendar` is using the default one for your locale. Have a look at the docstring of `Calendar` (or at the online [documentation](https://tkcalendar.readthedocs.io/en/stable/Calendar.html) and you will find all the info you need to do that. – j_4321 May 19 '21 at 07:47
  • But it always used to work with other things irrespective. Also, I have already been through the documentation and I used the code: `print(cal._get_date_pattern("dd-mm-yyyy"))` but it only prints out the string. "dd-mm-yyyy". How to add picture to comments? – Deven Jain May 19 '21 at 08:12

1 Answers1

3

First of all, in

 getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())

you are executing the function instead of passing it as an argument, like in Why is the command bound to a Button or event executed when declared?.

Then, according to the docstring of Calendar, it takes a date_pattern option

date_pattern : str
    date pattern used to format the date as a string. The default
    pattern used is babel's short date format in the Calendar's locale.

    A valid pattern is a combination of 'y', 'm' and 'd' separated by
    non letter characters to indicate how and in which order the
    year, month and day should be displayed.

        y: 'yy' for the last two digits of the year, any other number of 'y's for
           the full year with an extra padding of zero if it has less
           digits than the number of 'y's.
        m: 'm' for the month number without padding, 'mm' for a
           two-digit month
        d: 'd' for the day of month number without padding, 'dd' for a
           two-digit day

    Examples for datetime.date(2019, 7, 1):

        'y-mm-dd' → '2019-07-01'
        'm/d/yy' → '7/1/19'

So just pass date_pattern="dd-mm-yyyy" in argument when creating the Calendar.

Here is an example

from tkinter import Tk, Button
from tkcalendar import Calendar

def getCustomDate():
    print(cal.get_date())

root = Tk()

cal = Calendar(root,
               selectmode="day",
               firstweekday="monday",
               background="#0f8bff",
               foreground="black",
               disabledforeground="#a3bec7",
               bordercolor="grey",
               normalbackground="#d0f4ff",
               weekendbackground="#8ffeff",
               weekendforeground ="black",
               disabledbackground="99b3bc",
               date_pattern="dd-mm-yyyy")
cal.pack(pady=10)
getdat=Button(root, text="Get This Date",
              bg="#00ffde", command=getCustomDate)
getdat.pack()
root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61
  • Even I have read the documentation... sir, its not happening, the `._get_date_pattern("dd-mm-y")` just does not work whatsoever... This is what happens, I type: `print(cal._get_date_pattern("dd-mm-yyyy"))` but it only prints out the string. ```"dd-mm-yyyy"```. – Deven Jain May 19 '21 at 09:24
  • I also typed that ```date_pattern="dd-mm-yyyy"``` line in the code just as you just said but it just printed out: ```dd-MM-y``` and nothing else. – Deven Jain May 19 '21 at 09:29
  • Update: Now for some reason the thing is broken completely, it doesn't even print anything anymore, I don't know what has happened. – Deven Jain May 19 '21 at 09:34
  • Yet another Update: It keeps printing this now: ```>``` – Deven Jain May 19 '21 at 09:42
  • 1
    Can you run my whole code and see if it does what you expect? You shouldn't need to use `cal._get_date_pattern("dd-mm-yyyy")`, it's an internal method (i.e. not meant to be used), just use `.get_date()` – j_4321 May 19 '21 at 09:47
  • Yeah, I am not using ```cal._get_date_pattern("dd-mm-yyyy")``` anymore, I am using ```date_pattern="dd-mm-yyyy"``` while defining the Calendar. And yes, I made a fresh python file and your method works like a charm. It is for some reason not working at all in my ```main.py``` program that has the rest of the code. I triple checked the syntax and everything but after making the necessary changes, it just prints out: ```>``` now and nothing else. – Deven Jain May 19 '21 at 09:55
  • I am updating my question and providing screenshots... – Deven Jain May 19 '21 at 09:55
  • 1
    In your `main.py` you do `print(cal.get_date)` instead of `print(cal.get_date())` so it prints the function object instead of the selected date. – j_4321 May 19 '21 at 10:10
  • holy sh*t... Such a small mistake... and literally spent the last 1 hour wondering **"HOWWW"** Thank you so much for the help sir, I really appreciate it! – Deven Jain May 19 '21 at 10:25
  • I seriously cant thank you enough, **THANK YOU** – Deven Jain May 19 '21 at 10:28