Getting Tkinter Text contents before destruction

Eric Brunel eric_brunel at despammed.com
Thu Feb 9 09:24:42 EST 2006


On Mon, 6 Feb 2006 20:11:28 -0700, Bob Greschke <bob at greschke.com> wrote:

> Hi!
>
> I want to grab the contents of a Text widget when the frame it's on gets
> destroyed.  I tried TextWidget.bind("<Destroy>"... , but the widget is  
> gone
> before the call gets made, and I'd really hate to do something with the
> function that gets called with TextWidgetsFrame.bind("<Destroy>", ...,  
> since
> that one function handles all of the frames in the program...or would  
> that
> even work?
>
> How can I do this?

One way is to define the deletion callback for the text's parent window to  
get the text before the widget gets deleted. To do that, you can use  
text.winfo_toplevel() to get the parent Toplevel for your text widget,  
then define the callback via wdw.protocol('WM_DELETE_WINDOW', ...). Here  
is a detailed example:

-----------------------------------------------------
 from Tkinter import *

root = Tk()

txt = None

def openWdw():
   global txt
   wdw = Toplevel()
   frm = Frame(wdw)
   frm.pack(expand=1)
   txt = Text(frm)
   txt.pack()
   print txt.winfo_toplevel(), frm, root
   txt.winfo_toplevel().protocol('WM_DELETE_WINDOW', getText)

def getText():
   print txt.get(1.0, END)
   txt.winfo_toplevel().destroy()

Button(root, text='Go', command=openWdw).pack()

root.mainloop()
-----------------------------------------------------

This will of course only work if the only reason for which the text widget  
can be destroyed is if its parent window is closed.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"



More information about the Python-list mailing list