2009-04-20 5 views
0

진행중인 계산에 대해 사용자에게 알려주는 모니터 창을 실현하고 싶습니다. 그렇게하기 위해 나는 작은 수업을 썼다. 하지만 쉬운 방식으로 여러 모듈을 사용하고 싶기 때문에 classmethod와 함께 구현하려고 생각했습니다.Tkinter-Monitor-Window 클래스 메쏘드

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

를 또한, I는 표시 될 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가 작동하는 것 같다 또한 올바른 방법으로 접근 할 것 같다! 어떤 아이디어가 잘못되어 무엇이 버튼과 작동하지 않습니까?

건배, 필립

답변

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 솔루션이 작동하지 않는 이유를 아직도 이해할 수 없지만 솔루션이 내 문제를 해결합니다. 감사! –

관련 문제