Hi everyone,
I’ve found this code to enter the date that I’d like to use in tkinter but I’m having several issue:
import tkinter as tk
from datetime import datetime
class DateEntry(tk.Frame):
def __init__(self, parent, **kwargs):
years = kwargs.pop('years', (1900, 9999))
super().__init__(parent, **kwargs)
vcmd = (self.register(self._validate), '%W', '%V', '%v', '%P', '%S')
for name, text, v1, v2 in (('day', 'DD', 1, 31),
('month', 'MM', 1, 12),
('year', 'YYYY', years[0], years[1])):
e = tk.Entry(self, name=name, width=len(text) + 2, justify="center")
e.pack(side=tk.LEFT)
e.insert(0, text)
e._valid = (len(text), v1, v2)
e.config(validate="all", validatecommand=vcmd)
def get(self):
data = {}
for entry in [self.nametowidget(child) for child in self.children]:
text = entry.get()
data[entry.winfo_name()] = int(text) if text.isdigit() else None
return data
def _validate(self, widget, cmd, validate, value, text):
# get this entry reference
w = self.nametowidget(widget)
# Clear entry or do nothing
if cmd in ('focusin', 'forced') or value == '':
if not value.isdigit():
w.delete(0, tk.END)
# Set the 'validate' option again after edit
w.after_idle(w.config, {'validate': validate})
return True
# process key
elif cmd == 'key' and value.isdigit():
# get from this entry the valid parameter
l, v1, v2 = w._valid
# get the startswith chars if YYYY
if v1 > 1 and len(value) < l:
l2 = len(value)
v1, v2 = int(str(v1)[:l2]), int(str(v2)[:l2])
# allow leading zero in DD / MM
elif v1 == 1 and len(value) == 1 and int(value) == 0:
return True
# return True if all valid else False
return all((text.isdigit(), v1 <= int(value) <= v2, len(value) <= l))
# else return False
return False
This is how I’m using it
self.birthday = StringVar(self)
self.birthday.set('')
self.birthday=DateEntry(self, years=(1935, 2020))
self.birthday.place(relx=0.22, rely=0.16, height=25, width=100)
But when I try to write/save it in excel I’m getting 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)
File "C:/Users/pc/Desktop/file/project.py", line 196, in insert
sheet.cell(row=current_row + 1, column=8).value = self.bday_entry.get()
File "C:\Program Files (x86)\Python38-32\lib\site-packages\openpyxl\cell\cell.py", line 216, in value
self._bind_value(value)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\openpyxl\cell\cell.py", line 199, in _bind_value
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert {'day': 11, 'month': 11, 'year': 1999} to Excel
I’m struggling with this for a while now. If somebody could help I’d really appreciete.
Thank you all!