Tkinter: focus/text selection problem with tkFileDialog

I

Irmen de Jong

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?

TIA,
--Irmen de Jong


-----test.py----
import Tkinter, tkFileDialog

window=Tkinter.Tk()
txt=Tkinter.Text(window)
txt.insert(Tkinter.END,"Choose a file, then try to select me")
txt.pack()

name=tkFileDialog.askopenfilename()
txt.insert(Tkinter.END,"\nFile chosen: "+name)
window.mainloop()
 
P

Peter Otten

Irmen said:
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
 
I

Irmen de Jong

Peter said:
Irmen de Jong wrote:




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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top