Tkinter: focus/text selection problem with tkFileDialog

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Fri Apr 30 16:44:22 EDT 2004


Peter Otten wrote:

> Irmen de Jong wrote:
> 
> 
>>Hi,
>>I'm having trouble with the code below.
>>It's just a regular Tk text widget in which you can type and
>>select text as expected, however the call to
>>tkFileDialog.askopenfilename() seems to screw things up. After the file
>>dialog, I can no longer use the Text widget (typing, selecting, it doesn't
>>work anymore!) What am I doing wrong?
> 
> 
> No sure, but opening the dialog before entering the main loop could be the
> problem. The following modification seems to work:
> 
> import Tkinter, tkFileDialog
> 
> window = Tkinter.Tk()
> txt = Tkinter.Text(window)
> txt.insert(Tkinter.END, "Choose a file, then try to select me")
> txt.pack()
> 
> def openFile(event=None):
>     name = tkFileDialog.askopenfilename()
>     txt.insert(Tkinter.END, "\nFile chosen: " + name)
> 
> txt.focus_set()
> window.after_idle(openFile)
> window.mainloop()
> 
> Peter
> 

Okay, I didn't know about the after_idle, and still don't understand why
my first attempt resulted in the weird behavior I described. But hey,
with a bit of tweaking, it works now :-)

Also another weird thing: I found out (using my original code
without the after_idle) that if I inserted a tkMessageBox before the
mainloop(), that the 'correct' behavior of the Text box is restored!
...confused...

--Irmen.

P.S. I have now also discovered Fredrik Lundh's page:
  http://www.effbot.org/zone/tkinter-threads.htm   Interesting.



More information about the Python-list mailing list