Home > Software design >  How to check if year is a leap year
How to check if year is a leap year

Time:10-30

I can't figure out how to use the tk calender ui to print if the year selected is a leap year or no.


from tkinter import*
from tkcalendar import*

root=Tk()
root.title("Code project")

selectedDate = Label(root, text="")

def selectDate():
    myDate =my_Cal.get_date()
    selectedDate.config(text=myDate)
    selectedDate.pack()


my_Cal= Calendar(root, setmode = 'day', date_pattern = 'd/m/yy')
my_Cal.pack()

openCal = Button(root, text="Select Date", command=selectDate)
openCal.pack()

root.mainloop()

this is the code i have now and it outputs this:

enter image description here i want to know how to print if it is a leap year or not when the button is clicked

CodePudding user response:

Just create a function that parses the myDate variable and extracts the year and then use the rules to calculate if it is a leap year.

For example:

from tkinter import*
from tkcalendar import*

root=Tk()
root.title("Code project")

selectedDate = Label(root, text="")

def selectDate():
    myDate =my_Cal.get_date()
    if is_leap_year(myDate):  # add text to label to tell user if it's a leap year
        text = myDate   " It is a leap year!"
    else:
        text = myDate   " It isn't a leap year!"
    selectedDate.config(text=text)
    selectedDate.pack()

def is_leap_year(date):   # Check for leap year
    year = int(date.split("/")[-1])
    if not year % 4:         
        if not year % 100:   
            if not year % 400:
                return True
            return False
        return True
    return False


my_Cal= Calendar(root, setmode = 'day', date_pattern = 'd/m/yy')
my_Cal.pack()

openCal = Button(root, text="Select Date", command=selectDate)
openCal.pack()

root.mainloop()

CodePudding user response:

A year must fulfill the following criteria for it to be a leap year:

  • The year must be evenly divisible by 4;
  • If the year can also be evenly divided by 100, it is not a leap year; unless
  • The year is also evenly divisible by 400. Then it is a leap year.

source: https://www.timeanddate.com/date/leapyear.html

  • Related