Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter save text in editor

Tags:

python

tkinter

I went here: http://effbot.org/zone/vroom.htm And tried this out:

filename = raw_input("Filename?")
editor = Text()
editor.pack(fill=Y, expand=1)
editor.config(font="Courier 12")
editor.focus_set()
mainloop()
#save
f = open(filename, "w")
text = str(editor.get(0.0,END))
try:
    f.write(text.rstrip())
    f.write("\n")

However, I was given an error:

TclError: invalid command name ".40632072L"

How can i fix this problem? I'm not comfortable with object-oriented programming, so I would prefer an imperative solution (without any class keywords).

like image 538
leonneo Avatar asked Apr 26 '26 03:04

leonneo


1 Answers

The problem is that, after the mainloop finishes, all of your widgets, including editor, get destroyed, so you can't call editor.get.

What you want to do is add some code that stashes the value of editor in a plain old string while the main loop is running, and then use that variable. For example:

text=''
def stash(*args):
    global text
    text = str(editor.get(0.0,END))
editor.bind_all('<<Modified>>', stash)

Or, of course, do the simpler thing: write the file from within the GUI instead of after the GUI has exited. If you go look farther down the same page, you'll see how they do that.

like image 102
abarnert Avatar answered Apr 28 '26 17:04

abarnert