我想实现一个向用户报告正在进行的计算的监视器窗口。为此,我写了一个小类。但是因为我想以一种简单的方式在不同的模块中使用它,所以我想用类方法来实现它。这允许在没有实例的情况下以下列方式使用它:
from MonitorModule import Monitor
Monitor.write("xyz")
此外,如果我在其他模块中使用它,则other_module.py中的Monitor.write()的输出将显示在同一窗口中。
我可以在每个模块中导入它以将特定输出重定向到同一监视器。我让它工作了,除了一件我不明白的小事。我无法使用我编写的特定处理程序关闭监视器窗口。我可以使用非类方法方式但不能使用处理程序作为类方法。
看代码:
import Tkinter
class Monitor_non_classmothod_way(object):
def __init__(self):
self.mw = Tkinter.Tk()
self.mw.title("Messages by NeuronSimulation")
self.text = Tkinter.Text(self.mw, width = 80, height = 30)
self.text.pack()
self.mw.protocol(name="WM_DELETE_WINDOW", func=self.handler)
self.is_mw = True
def write(self, s):
if self.is_mw:
self.text.insert(Tkinter.END, str(s) + "\n")
else:
print str(s)
def handler(self):
self.is_mw = False
self.mw.quit()
self.mw.destroy()
class Monitor(object):
@classmethod
def write(cls, s):
if cls.is_mw:
cls.text.insert(Tkinter.END, str(s) + "\n")
else:
print str(s)
@classmethod
def handler(cls):
cls.is_mw = False
cls.mw.quit()
cls.mw.destroy()
mw = Tkinter.Tk()
mw.title("Messages by NeuronSimulation")
text = Tkinter.Text(mw, width = 80, height = 30)
text.pack()
mw.protocol(name="WM_DELETE_WINDOW", func=handler)
close = handler
is_mw = True
a = Monitor_non_classmothod_way()
a.write("Hello Monitor one!")
# click the close button: it works
b = Monitor()
Monitor.write("Hello Monitor two!")
# click the close button: it DOESN'T work, BUT:
# >>> Monitor.close()
# works...
因此,classmethod 似乎有效,并且似乎可以以正确的方式访问!任何想法,出了什么问题,它不适用于按钮?
干杯,菲利普