I have a (second) tkinter window, which, when opened, does not get the focus, but rather the first window remains focused (although the second window appears in front of the other). It contains a textbox which I want to be able to type in, but I have to double-click it in order to type.
How do I focus the textbox when opening the window?
My tries:
textbox.focus_set()
,
window.grab_set()
,
window.focus_set()
None of them did what I wanted to do.
EDIT:
Instead, .focus_set()
raises an error when (and only when) closing the main window: can't invoke "focus" command: application has been destroyed
This is my current code (tkWin
is the main window, tkcWin
is the second window):
def click(self, field):
import _tkinter
if field != None:
try:
self.tkcWin = Tk()#creating window
self.tkcWin.focus()
self.tkcWin.title(field)
self.tkcWin.geometry('300x100')
self.mainframe = Frame(master=self.tkcWin,background="#60BF98")
self.mainframe.place(x=0, y=0, width=300, height=300)
self.textb = Text(master=self.mainframe)
self.textb.place(x=0, y=50)
self.textb.bind("<Return>",lambda a: self.setM(field))
self.textb.bind("<Return>",lambda a: self.tkcWin.destroy(),True)
self.tkcWin.grab_set()
self.tkWin.wait_window(self.tkcWin)
self.textb.focus_set()
hwnd = self.tkcWin.winfo_id()
ctypes.windll.user32.SetFocus(hwnd)
self.tkcWin.mainloop()
except _tkinter.TclError:
self.tkcWin.destroy()