Search code examples
pythontkintertkinter-entrysetfocus

How to get tkinter to focus in on entry box on initializing new window?


I am trying to use tkinter to create a new window with the focus set on its entry box. I am using the following code, which as far as I can tell should work:

import tkinter as tk

m = tk.Tk(className="My window")
def clickclack():
    new = tk.Tk(className="New")
    entr = tk.Entry(new)
    entr.grid()
    entr.focus_set()

butt = tk.Button(m, text="My button", width=25, command=clickclack)
butt.grid()
m.mainloop()

However, when I run it and click on the button, although a new window with an entry box pops up, the focus is not on it. I am not sure why focus_set() isn't working here, any help would be appreciated.


Solution

  • It is not recommend to use many Tk instance at the same time.Another window should use Toplevel instance.(Maybe will cause StringVar()(and so on) couldn't work normally).

    Due to Toplevel didn't have attribute className,if you want to set the title name for the new window,you need to use Toplevel().title("xxxxx").

    Also,you could make your Toplevel focused firstly,then make your Entry widget focuesed.

    Try:

    import tkinter as tk
    
    m = tk.Tk(className="My window")
    def clickclack():
        new = tk.Toplevel()
        new.title("New") # set title
        entr = tk.Entry(new)
        entr.grid()
        new.focus() # make the window focused
        entr.focus()
    
    butt = tk.Button(m, text="My button", width=25, command=clickclack)
    butt.grid()
    m.mainloop()