I am trying to build a basic example UI with tkinter/ttk. This interface has a ttk.Entry field and a ttk.Button, it basically just clears the content in the entry field, and set the focus back to the entry field
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
def doSomething(event, entryField):
messagebox.showwarning('', 'Warning')
entryField.delete(0, END)
entryField.focus_set()
entryField.focus()
root = Tk()
entryField = ttk.Entry(root)
entryField.grid(row=0, column=0)
entryField.focus()
b = ttk.Button(root, text='Clear and focus back')
b.grid(row=1, column=0)
b.bind('<Button-1>',
lambda event, entryField=entryField:
doSomething(event, entryField))
root.mainloop()
The problem is it does not focus back to the entry field after the warning message. The code works If I use Entry instead of ttk.Entry
I am not sure about the cause, but you can workaround it by using root.after
:
def doSomething(event, entryField):
messagebox.showwarning('', 'Warning')
entryField.delete(0, END)
root.after(1, lambda: entryField.focus_set())