[Tkinter-discuss] widget focus switching problems.

Michael Lange klappnase at web.de
Mon Oct 15 20:54:22 CEST 2007


On Sat, 13 Oct 2007 03:52:43 -0500
Nicholas <nicholaskriz at gmail.com> wrote:

> I'm having difficulty switching focus between widgets in my program. This  
> is a mostly non-functioning GUI to be used for database creation, saving  
> and retreival. The code currently looks horrifyingly unPythonic since I'm  
> very new to this and I'm just kind of hacking my way through it. It's also  
> several hundred more lines than I should put in here. My major question is  
> if there is a Python or Tkinter piece of code that will excecute itself as  
> though I had pressed the tab button? In other words, I'd like to bind the  
> return key, when pressed in my Entry box, to switch focus (or Tab) to the  
> next item in the focus loop. I have the focus turned off for all other  
> widgets aside from the ones created by the function below and one button  
> (the one that will save the entries to the db). Sorry if this is  
> long-winded, but I'm not sure what I'm talking about enough to be concise.  
> Anyway, here's the code so far and what I think it does:
> 
> ##########################
> 
> variables = []					# clears previously collected values
> for field in SHORTKEYS:				# iterates over a list of 40 items
>      ent = Entry(rite)				# creates the entry box
>      ent.pack(side = TOP, fill = X)		# packs the entry box
>      if field == 'name':				# 'name' is the first entry box,
>          ent.focus_set()				# so it gets focus on startup
>      ent.bind('<Return>', return_pressed)	# binds <Return> on all entry  
> boxes
>      var = StringVar()				#
>      ent.config(textvariable=var)		# all the other lines convert the entries
>      variables.append(var)			# to a list I can use later.
> return variables				#
> 

Hi Nick,

you will want to use the widget's event_generate() method to emulate the Tab-keystroke,
so your callback might look like:

    def return_pressed(event):
        event.widget.event_generate('<Tab>')
        return 'break'

The "return 'break'" statement stops the <Return> event from triggering its default callback (if any).
I hope this helps.

Michael



More information about the Tkinter-discuss mailing list