Python Forum
Convert combobox user input in to date with tkinter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert combobox user input in to date with tkinter
#1
Hi!
I'm having a little bit of difficulty with a couple of things with my script:

from datetime import datetime
from tkinter.ttk import *
from tkinter import *
from openpyxl import *


class Application(Tk):
   def __init__(self, *args, **kwargs):
       Tk.__init__(self, *args, **kwargs)

       d29 = list(range(1, 30))
       d30 = list(range(1, 31))
       d31 = list(range(1, 32))


       self.months = dict(
           January=d31,
           February=d29,
           March=d31,
           April=d30,
           May=d31,
           June=d30,
           July=d31,
           August=d31,
           September=d30,
           October=d31,
           November=d30,
           December=d31)

       self.lbl_birth = Label(self, text="Birthday:", font=('times', 14))
       self.lbl_birth.grid(row=1, column=1)

       self.cb_day = Combobox(self, values=self.months["January"])
       self.cb_day.grid(row=1, column=2)
       self.cb_day.set("1")

       self.cb_month = Combobox(self, values=[*self.months])
       self.cb_month.bind('<<ComboboxSelected>>', self.update)
       self.cb_month.grid(row=1, column=3)
       self.cb_month.set("January")

       self.cb_year = Combobox(self, values=list(range(1996, 2006)))
       self.cb_year.grid(row=1, column=4)
       self.cb_year.set("2000")


       items = [self.lbl_birth, self.cb_day, self.cb_month, self.cb_year]
       for t in items:
           self.grid_columnconfigure(t, weight=1)
           self.grid_rowconfigure(t, weight=1)

   def update(self, event):
       self.cb_day["values"] = self.months[self.cb_month.get()]
       self.cb_day.set("1")


if __name__ == "__main__":
   app = Application()
   app.title('My Birthday App')
   app.mainloop() 
When I'm writing in excel using this code:
        self.bday = self.cb_day.get(), self.cb_month.get(), self.cb_year.get()
        self.birthday = str(self.bday)
        sheet.cell(row=3, column=5).value = self.birthday
I get something like this:
('1', 'January', '2000')
I've tried strftime and strptime to convert self.bday in a proper date format but without success (I always get some errors). Also I'm trying to calculate the age in years with this:
        today_year = datetime.now().strftime('%Y')

        age = int(today_year) - int(self.cb_year.get())
        print(age)
It kinda works, but I always get back "20", as if self.cb_year.get() only gives me back the default year i put in set() and not the user input.
I really can't solve this by myself so thank you all for your help!
Reply
#2
from datetime import datetime

day, month, year = ('1', 'January', '2000')
mydate = datetime.strptime(f'{day} {month} {year}', '%d %B %Y')
print(mydate)
today = datetime.now()
print(today)
years = today.year - mydate.year
print(years)
Output:
2000-01-01 00:00:00 2020-06-29 22:21:04.644274 20
Reply
#3
(Jun-29-2020, 09:22 PM)Yoriz Wrote:
from datetime import datetime

day, month, year = ('1', 'January', '2000')
mydate = datetime.strptime(f'{day} {month} {year}', '%d %B %Y')
print(mydate)
today = datetime.now()
print(today)
years = today.year - mydate.year
print(years)
Output:
2000-01-01 00:00:00 2020-06-29 22:21:04.644274 20

Thanks! That worked, but I'm only getting the date based on 2000-01-01. When I try to change the month it gives me back this error:
"Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
TypeError: update() takes 1 positional argument but 2 were given"
How can I get the all the age and the birthday that may be inserted?
Thanks again
Reply
#4
I can't find the edit button so I apologize in advance for the double post, I've solved the traceback error, but I still only get the default date that I inputted (2000,01,01). How can I get the user info from the combobox?
Thank you for your help
Reply
#5
Can you show the full code you have now
Reply
#6
This is my code right now:
from datetime import datetime
from tkinter.ttk import *
from tkinter import *
from openpyxl import *


class Application(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        d29 = list(range(1, 30))
        d30 = list(range(1, 31))
        d31 = list(range(1, 32))

        self.months = dict(
            January=d31,
            February=d29,
            March=d31,
            April=d30,
            May=d31,
            June=d30,
            July=d31,
            August=d31,
            September=d30,
            October=d31,
            November=d30,
            December=d31)

        self.lbl_birth = Label(self, text="Birthday:", font=('times', 14))
        self.lbl_birth.grid(row=1, column=1)

        self.cb_day = Combobox(self, values=self.months["January"])
        self.cb_day.grid(row=1, column=2)
        self.cb_day.set("1")

        self.cb_month = Combobox(self, values=[*self.months])
        self.cb_month.bind('<<ComboboxSelected>>', self.update)
        self.cb_month.grid(row=1, column=3)
        self.cb_month.set("January")

        self.cb_year = Combobox(self, values=list(range(1996, 2006)))
        self.cb_year.grid(row=1, column=4)
        self.cb_year.set("2000")

        day, month, year = self.cb_day.get(), self.cb_month.get(), self.cb_year.get()
        mydate = datetime.strptime(f'{day} {month} {year}', '%d %B %Y')
        today = datetime.now()
        years = today.year - mydate.year

        
    def update(self, event):
        self.cb_day["values"] = self.months[self.cb_month.get()]
        self.cb_day.set("1")


if __name__ == "__main__":
    app = Application()
    app.title('My Birthday App')
    app.mainloop()
Thank you
Reply
#7
Your code is grabbing the values of the Combobox's immediately after creating them.
You need to have a GUI selection made first and then possibly a button to click to submit the relevant Combobox selections.
The event from clicking the button would then read the current Combobox values.

I think I see now that you want the year calculated when any combobox value changes
from datetime import datetime
from tkinter.ttk import *
from tkinter import *
from openpyxl import *
 
 
class Application(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
 
        d29 = list(range(1, 30))
        d30 = list(range(1, 31))
        d31 = list(range(1, 32))
 
        self.months = dict(
            January=d31,
            February=d29,
            March=d31,
            April=d30,
            May=d31,
            June=d30,
            July=d31,
            August=d31,
            September=d30,
            October=d31,
            November=d30,
            December=d31)
 
        self.lbl_birth = Label(self, text="Birthday:", font=('times', 14))
        self.lbl_birth.grid(row=1, column=1)
 
        self.cb_day = Combobox(self, values=self.months["January"])
        self.cb_day.bind('<<ComboboxSelected>>', self.update)
        self.cb_day.grid(row=1, column=2)
        self.cb_day.set("1")
 
        self.cb_month = Combobox(self, values=[*self.months])
        self.cb_month.bind('<<ComboboxSelected>>', self.update)
        self.cb_month.grid(row=1, column=3)
        self.cb_month.set("January")
 
        self.cb_year = Combobox(self, values=list(range(1996, 2006)))
        self.cb_year.bind('<<ComboboxSelected>>', self.update)
        self.cb_year.grid(row=1, column=4)
        self.cb_year.set("2000")
 
        
 
         
    def update(self, event):
        day, month, year = self.cb_day.get(), self.cb_month.get(), self.cb_year.get()
        mydate = datetime.strptime(f'{day} {month} {year}', '%d %B %Y')
        today = datetime.now()
        years = today.year - mydate.year
        print(f'Years: {years}')
 
 
if __name__ == "__main__":
    app = Application()
    app.title('My Birthday App')
    app.mainloop()
Reply
#8
Thank you, it worked! I'm very happy: I've finish my first app thanks to you. I've only a couple of question, but they are really just about style, you've already help me a lot so don't mind me if I bother you too much. My questions are:
Is there a way to have a leading zero on the day of the month? Basically add it in this part.
 d29 = list(range(1, 30))
        d30 = list(range(1, 31))
        d31 = list(range(1, 32))
And also is there a way to format the date without all the zero? From this 01/01/2000 00:00:00 to this 01/01/2000.
Once again, you help me a lot! Thank you
Reply
#9
from datetime import datetime
 
day, month, year = ('1', 'January', '2000')
mydate = datetime.strptime(f'{day} {month} {year}', '%d %B %Y')
print(mydate.strftime('%d/%m/%Y'))


d29 = list(f'{num:02}' for num in range(1, 30))
print(d29)
Output:
01/01/2000 ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGUI] [Solved]Help storing in user input from line edit Extra 2 1,678 May-12-2022, 07:46 PM
Last Post: Extra
  [PyQt] How can I sync Combobox index to other combobox index? nickzsche 2 2,329 Jan-03-2022, 12:29 PM
Last Post: Axel_Erfurt
  Convert tkinter to pyqt razs 6 5,462 Aug-29-2021, 11:08 AM
Last Post: razs
Question [Tkinter] Can I set background color for each item in tkinter Combobox? water 1 5,055 Dec-10-2020, 07:48 PM
Last Post: Larz60+
  [Tkinter] Getting Input from Tkinter Entry juliabrushett 6 21,213 May-30-2020, 03:29 PM
Last Post: Larz60+
  Create an identification code from user input PeroPuri 1 1,870 Apr-11-2020, 11:56 AM
Last Post: Larz60+
  How can a user send a message via Contact Form in tkinter karolp 0 2,318 Apr-08-2020, 08:00 PM
Last Post: karolp
  [PyQt] Python PyQt5 - Change label text dynamically based on user Input ppel123 1 13,657 Mar-20-2020, 07:21 AM
Last Post: deanhystad
  [Tkinter] Tkinter delete combobox content and not the list LagratteCchouette 4 8,342 Dec-29-2019, 11:04 AM
Last Post: LagratteCchouette
  PyQt5: How do you set the user input of a line edit to a specific variable? YoshikageKira 17 11,468 Dec-26-2019, 03:18 PM
Last Post: Denni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020