pythontkintercustomtkinter

CustomTKinter entry not getting focus


I'm trying to set the focus to my entry but, it just doesn't work! I tried with normal TKinter and the focus_set method worked fine, any help plsss??

import customtkinter

customtkinter.set_appearance_mode('dark')  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme('green')  # Themes: "blue" (standard), "green", "dark-blue"

app = customtkinter.CTk()
app.geometry('220x155')
app.title('Program')
app.eval('tk::PlaceWindow . center')

frame_1 = customtkinter.CTkFrame(master=app)
frame_1.pack(pady=5, padx=5, fill="both", expand=True)

title = customtkinter.CTkLabel(master=frame_1, text="Title", font=customtkinter.CTkFont(size=20, weight='bold'))
title.pack(pady = 1, padx = 1)

text = customtkinter.CTkLabel(master=frame_1, text="Label", font=customtkinter.CTkFont(size=10))
text.pack(pady = 5, padx = 5)

entry = customtkinter.CTkEntry(master=frame_1)
entry.focus_set()
entry.pack()


def imprime(event=None):
    print('txt')

def imprime2():
    print('txt2')

app.bind('<Return>', imprime)
ligar = customtkinter.CTkButton(master=frame_1, text='button', command = imprime2)
ligar.pack(pady=5, padx=5)

app.mainloop()

I want my window app to open and that my entry field gets de focus so I don't have to click it to start typing.


Solution

  • I think you're running into a timing issue, as in the widget hasn't been fully created when you try to give it focus. Try this:

    entry = customtkinter.CTkEntry(master=frame_1)
    app.update()
    entry.focus_set()
    entry.pack()