我知道ScrolledText被构造为Text对象(但在框架中具有附加的滚动条)。但是,当关闭窗口并printText()
调用该方法时,以下代码将引发错误:
import Tkinter as tk
import ttk
import ScrolledText as st
class tkGui(object):
def printText(self, event):
print "It works!"
self.mText.get("1.0", 'end-1c')
def __init__(self, window):
# create widgets
self.frame=tk.Frame(window)
self.mText = st.ScrolledText(self.frame)
self.mText.bind('<Destroy>',self.printText)
# place widgets
self.frame.pack()
self.mText.pack()
window = tk.Tk()
app = tkGui(window)
window.mainloop()
错误:
[...]
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3077, in get
return self.tk.call(self._w, 'get', index1, index2)
TclError: invalid command name ".140506094171344.140506094172280.140506094172496"
我究竟做错了什么?
销毁主窗口后,其所有子部件都将销毁,并且您将无法访问它们。(这在技术上是不正确的,正如布莱恩·奥克利(Bryan Oakley)的答案所指出的那样,但这是我的想法。在销毁后尝试使用这些小部件充其量是有问题的。)
您需要使用 wm_protocol
http://nullege.com/codes/search/Tkinter.Tk.wm_protocol
import Tkinter as tk
import ttk
import ScrolledText as st
class tkGui(object):
def printText(self):
print "It works!"
self.mText.get("1.0", 'end-1c')
self.window.destroy()
def __init__(self, window):
# create widgets
self.window = window
self.frame=tk.Frame(window)
self.mText = st.ScrolledText(self.frame)
#self.mText.bind('<Destroy>',self.printText)
window.wm_protocol("WM_DELETE_WINDOW", self.printText)
# place widgets
self.frame.pack()
self.mText.pack()
window = tk.Tk()
app = tkGui(window)
window.mainloop()
这里有几个更改。我从中删除了event
参数,printText
并添加了对的调用self.window.destroy
。请注意,我必须添加self.window
属性才能进行此调用。基本的更改是使用wm_protocol而不是绑定到事件。其他都是必然的后果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句