3

我去了这里:http ://effbot.org/zone/vroom.htm 并尝试了这个:

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")

但是,我收到了一个错误:

TclError: invalid command name ".40632072L"

我该如何解决这个问题?我对面向对象编程不满意,所以我更喜欢命令式解决方案(没有任何class关键字)。

4

1 回答 1

3

问题是,在 mainloop 完成后,您的所有小部件,包括editor,都会被销毁,因此您无法调用editor.get.

您想要做的是添加一些代码,editor在主循环运行时将值存储在一个普通的旧字符串中,然后使用该变量。例如:

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

或者,当然,做更简单的事情:从 GUI 中写入文件,而不是在 GUI 退出之后。如果你再往下看同一页,你会看到他们是如何做到的。

于 2013-10-18T10:23:17.297 回答