Home > Back-end >  How to put in if statement date format for entry in tkinter?
How to put in if statement date format for entry in tkinter?

Time:02-21

 def Verification():
    date_format = "%d/%m/%Y"
    
    if (datetime.strptime("1/1/2001", date_format) <= date_ < datetime.strptime("31/1/2008", date_format)):
        print('bravo')
    date_= datetime.strptime(date_,date_format)
    vt=date_
vt =StringVar()
vt.set('')
lb = Label(parent, text = 'birth day:  ')
cp = Entry(parent, textvariable=vt)
bt = Button(parent, text ='Verify', command = Verification)
lb.place(x=30, y=90)
cp.place(x=95, y=90)
bt.place(x=220,y=90) 

CodePudding user response:

I'm not sure I understand your question, so the following is an answer based on what I think you're asking.

It works like this: When the Verify button is pressed the verification() function will be called which will initially attempt to parse what the user inputted into a datetime instance. If it cannot do that a error message indicating that will appear. If it succeeds then it next checks to see if it's in the required date range. Again, displaying an error message if it isn't.

from datetime import datetime
from tkinter import *
import tkinter.messagebox as messagebox


DATE_FORMAT = "%d/%m/%Y"
MIN_DATE = datetime.strptime('1/1/2001', DATE_FORMAT)
MAX_DATE = datetime.strptime('31/1/2008', DATE_FORMAT)


def verification():
    try:
        date_= datetime.strptime(vt.get(), DATE_FORMAT)
    except ValueError:
        messagebox.showerror('Invalid Date', f'"{vt.get()}"')
        return

    if MIN_DATE <= date_ < MAX_DATE:  # Check date range.
        messagebox.showinfo('Bravo', "You entered a valid date!")
    else:
        messagebox.showerror('Out of range', vt.get())


parent = Tk()
parent.geometry('300x200')

vt = StringVar(value='D/M/Y')  # Initially show required format.

lb = Label(parent, text='birth day:  ')
cp = Entry(parent, textvariable=vt)
bt = Button(parent, text ='Verify', command=verification)

lb.place(x=30, y=90)
cp.place(x=95, y=90)
bt.place(x=220,y=90)

parent.mainloop()

Screenshot of it running:

Screenshot

  • Related