2009-04-20 9 views
0

進行中の計算についてユーザに報告するモニタウィンドウを実現したいと思います。そうするために私は小さなクラスを書いた。しかし、簡単な方法で異なるモジュール間で使用したいので、クラスメソッドで実装することを考えました。Tkinter-Monitor-Windowのクラスメソッド

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

をまた、Iは、表示されother_module.py内で、他のモジュールにMonitor.write()の出力をそれを使用する場合:これは、インスタンスなしで次のようにそれを使用することができ同じウィンドウ。

これを各モジュールでインポートして、特定の出力を同じモニターにリダイレクトすることができます。私はそれが私が理解していない小さな事を除いて働きました。私は、私が書いた特定のハンドラでMonitorウィンドウを閉じることはできません。私はクラスメソッドではなくクラスメソッドとしてハンドラではできません。コードで

ルック:

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

あなただけの複数のモジュール間でオブジェクトを使用することを容易にするためにクラスメソッドの多くを必要としません。

ここに示すように、代わりにモジュールのインポート時にインスタンスを作る考えてみます。

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の解決策が機能しない理由を理解できませんが、あなたの解決策は私の問題を解決します。ありがとう! –