2009-04-20 48 views
0

我想实现一个监视窗口,向用户报告正在进行的计算。为此我写了一个小课。但是,因为我想以一种简单的方式在不同的模块中使用它,所以我想用classmethods来实现它。这允许使用它以下面的方式无实例:也Tkinter-Monitor-Window的classmethod

from MonitorModule import Monitor 
Monitor.write("xyz") 

,如果我的其它模块中使用它,Monitor.write()的输出内other_module.py将显示在同一个窗口。

这我可以在每个模块导入重定向特定的输出到同一个显示器。除了一件我不明白的东西外,我找到了它。我无法关闭与我写的特定处理程序的监视器窗口。我可以用非类方法来做到这一点,但不能用处理器作为类方法。

看代码:

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... 

所以,类方法似乎工作,也似乎是在正确的方式访问!任何想法,出了什么问题,它不适用于按钮?

干杯,菲利普

回答

3

你并不需要太多的classmethods只是为了可以很容易地跨越多个模块的目标。

而是考虑在模块导入时作出的实例如下所示:

import Tkinter 

class Monitor(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() 

monitor = Monitor() 

other_module.py

from monitor import monitor 
monitor.write("Foo") 
+0

,真正起作用。虽然我仍不明白为什么classmethod解决方案无法正常工作,但您的解决方案解决了我的问题。谢谢! – 2009-04-22 08:24:38

相关问题