自分で開いたウィンドウを自分で閉じるプログラム
ウィンドウを開くのだが、ある条件になったときに開いたウィンドウを自動的に閉じたい場合が多々ある。閉じる条件はいろいろあり、閉じる方法もまたいろいろ考えられる。
ここでは、次々更新される外部ファイルの内容を読み取って、そのファイルの中に特定の文字列が見つかった場合に、自分自身で開いたウィンドウを終了させるプログラムを作ってみる。それは下のようになる。
import wx TIMER_INTERVAL = 1000 class myPlot(wx.Panel): def __init__(self, parent): self.parent = parent self.Start() def Start(self): self.timer1 = wx.Timer(self.parent) self.parent.Bind(wx.EVT_TIMER, self.check_file, self.timer1) self.timer1.Start(TIMER_INTERVAL) def check_file(self, event): try: fp = open('ReadMe', 'r') except: return False lines = fp.readlines() fp.close() for i in lines: try: if i.find("temporary") != -1: self.parent.Close() except: pass if __name__ == '__main__': app = wx.App() frame = wx.Frame(None, title="self-close window", size=(300,250)) panel = myPlot(frame) frame.Show() app.MainLoop()
外部ファイルの内容確認は、wxTimerを使って一定時間ごとに実行されるようにしている。ファイルの中に文字列「temporary」が見つかったら、自分で開いたウィンドウを閉じる。