Leo
Leo

Reputation: 659

Setting focus to specific TKinter entry widget

I'd like to set the focus of my program to a specific entry widget so that I can start entering data straight-away - how can I do this?

My current code

from Tkinter import *
root = Tk()
frame=Frame(root,width=100,heigh=100,bd=11)
frame.pack()
label = Label(frame,text="Enter a digit that you guessed:").pack()
entry= Entry(frame,bd=4)
entry.pack()

button1=Button(root,width=4,height=1,text='ok')
button1.pack()

root.mainloop()

Upvotes: 29

Views: 56644

Answers (3)

Martin Hummel
Martin Hummel

Reputation: 11

Assume you have multiple entries and you wish to focus, simply by hovering the mouse pointer, without having to click on entries all the time. I was searching and could not find an example, so I figured it out. Please see below, sharing the result of my little research:

 import tkinter as tk
 
 root = tk.Tk() 
 root.title("Multiple Entries") 
 root.geometry("320x100")
 
 def go_focus(event):
     """ push focus on widget just entered
     """
     event.widget.focus()
 
 tk.Label(root,text='Entry 1:').grid(row=1,column=1)
 tk.Label(root,text='Entry 2:').grid(row=2,column=1)
 tk.Label(root,text='Entry 3:').grid(row=3,column=1)
 
 entry1 = tk.Entry(root) 
 entry2 = tk.Entry(root) 
 entry3 = tk.Entry(root)
 
 entry1.grid(row=1,column=2) 
 entry2.grid(row=2,column=2)
 entry3.grid(row=3,column=2)
 
 entry1.bind('<Any-Enter>',func=go_focus)
 entry2.bind('<Any-Enter>',func=go_focus)
 entry3.bind('<Any-Enter>',func=go_focus)

Note: Wherever the mouse hovers, the cursor will appear and keyboard input will land inside that specific entry.

Upvotes: 1

osama beshara
osama beshara

Reputation: 121

I tried this way and it is ok

entry= Entry(root)
entry.focus()
entry.pack

Upvotes: 6

unutbu
unutbu

Reputation: 880777

Use entry.focus():

from Tkinter import *
root = Tk()
frame=Frame(root,width=100,heigh=100,bd=11)
frame.pack()
label = Label(frame,text="Enter a digit that you guessed:").pack()
entry= Entry(frame,bd=4)
entry.pack()
entry.focus()
button1=Button(root,width=4,height=1,text='ok')
button1.pack()

root.mainloop()

Upvotes: 48

Related Questions