2

I have a DateEntry widget and a button to clear the DateEntry contents. I want the DateEntry to be blank unless the user selects a date.

My problem is if I select the DateEntry widget and give it focus, then using the clear button doesn't work the first time because the DateEntry is auto-completing after losing focus.

Example:

from tkinter import *
from tkinter import ttk
from tkcalendar import DateEntry

def clearDateEntry():
    clearButton.focus_set()
    myDateEntry.delete(0,END)

root=Tk()

myDateEntry=DateEntry(root)
myDateEntry.pack()
myDateEntry.delete(0,END)

clearButton=Button(root,text='clear',command=clearDateEntry)
clearButton.pack()

root.mainloop()

To replicate: give DateEntry focus, then click clear.

In the clearDateEntry() function, I move the focus to the clear button first which I'd expect would trigger the auto-complete so that I can delete it straight after, but that doesn't work.

How do I make clearDateEntry() actually clear the DateEntry on the first go? If there's a way to turn off DateEntry's auto-complete, that would also solve my problem.

j_4321
  • 15,431
  • 3
  • 34
  • 61
Rory LM
  • 160
  • 2
  • 15

2 Answers2

3

The DateEntry is set to validate the entry content on focus out (the validate option is set to 'focusout') and if the content is not a valid date, today's date is put in the entry. The idea being to always have a valid date inside the entry.

You can therefore simply get rid of this behavior by setting

myDateEntry.configure(validate='none')

This way the entry content is no longer validated on focus out, however it will still be validated when clicking on the drop-down button so there shouldn't be issue with invalid dates when displaying the calendar.

j_4321
  • 15,431
  • 3
  • 34
  • 61
1

The easiest way is to delay your delete method by 1 ms:

def clearDateEntry():
    clearButton.focus_set()
    root.after(1, myDateEntry.delete, 0,END)
Henry Yik
  • 22,275
  • 4
  • 18
  • 40