how to develop windform using python

8209 ワード

方法1:PyQT
Qtはプラットフォームをまたぐインターフェースライブラリで、PyQtはPythonバージョンです。PythonのインターフェースライブラリはPyQtのほかに、wxPython、TKなどがあります。環境:Windows+Python 2.6+Qt 1.ダウンロードインストール環境python 2.6:www.python.org PyQt 2.6:http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7-1.exe eric 4:http://nchc.dl.sourceforge.net/project/eric-ide/eric4/stable/4.4.0/eric4-4.4.0.zip eric 4はPyQtインターフェースコンパイラであり、PythonのIDEとしてeric 4をインストールした後、Python 26\Lib\site-packages\eric 4\目次の下にeric 4.pywファイルがあります。ダブルクリックして、eric 4エディタを開けました。初めて開けたら、設定ウィンドウがあります。簡単に配置してください。eric 4.appiまたは他のAPIを選択してください。次に「Comple API」をクリックすると、時間がかかります。終了後にAppleを注文して、配置は終了します。2.demo 2.1 Project->New、新しいプロジェクトを作ってハローと名付けましょう。2.2エディタの左のProject-Viewerの中の第二のタブFormsをクリックして、空白のところで右クリックします。New Form、ポップアップダイアログはDialogを選択し、Helloと命名します。保存後、自動的にQt 4のデザインウィンドウをイジェクトします。2.3デザインウィンドウの左に2つのボタンを引くと、btnClick、btnExit、Edit枠2.4を引くというウィンドウをクリックします。のプラス記号(+)は、定義されていないイベントが発生します。このとき、送信者がbtnExitを選択し、信号の中でclicked()を選択し、受信者の中でDialogを選択し、スロットの中でclose()を選択して保存してから、デバイスを閉じます。2.5 ericインターフェイスで、FromタブにHello.uiというファイルが現れます。ファイル名の右ボタンでComple Formを選択し、Generate Dialog Codeを選択して、Class Nameを設定して、右のNewボタンをクリックして、デフォルトでいいです。確定したら、下のテキストボックスからbtnClickの下の最初のon_を選択します。btnClick_clicked()にチェックを入れてOKし、Project-Viewerの下の最初のタブSourceに戻り、Hello.pyをダブルクリックして、次のように修正します。
def on_btnClick_clicked(self):   
    """  
    Slot documentation goes here.  
    """  
    # TODO: not implemented yet   
    #raise NotImplementedError   
    self.editTxt.setText("Hello, PyQt!")  
    def on_btnClick_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        #raise NotImplementedError
        self.editTxt.setText("Hello, PyQt!") 
 
追加:
if __name__ == '__main__':   
        app = QApplication(sys.argv)   
           
        dlog = Dialog()   
        dlog.show()   
           
        sys.exit(app.exec_())  
if __name__ == '__main__':
        app = QApplication(sys.argv)
        
        dlog = Dialog()
        dlog.show()
        
        sys.exit(app.exec_()) 
 F 5で運転します
 
方法二:
wxPythonはwxWidgetsに基づくクロスプラットフォームインターフェースライブラリである。
環境はWindows XP+Pythoon 2.6+wxPythoon 2.8です。wxPythonダウンロードアドレス:http://downloads.sourceforge.net/project/wxpython/wxPython/2.8.9.2/wxPython2.8-win32-unicode-2.8.9.2-py26.exe?use_mirror=nchc1.最初のデモ(提供されたPySimpleAPPを使用して)は、デモについて、まずcodeに来てから説明します。
#coding=utf8   
#!usr/bin/env python   
  
import wx   
class MyFrame(wx.Frame):   
    def __init__(self):   
        print 'MyFrame.__init__'  
        wx.Frame.__init__(self, None, -1, "demo1", size=(300,400))   
        panel = wx.Panel(self, -1)   
        panel.Bind(wx.EVT_MOTION, self.OnMove)   
        wx.StaticText(panel, -1, "Pos:", pos=(10,12))   
        self.posCtrl = wx.TextCtrl(panel, -1, "", pos=(40,10))   
           
    def OnMove(self, event):   
        pos = event.GetPosition()   
        self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))   
           
           
if __name__ == '__main__':   
#    app = wx.PySimpleApp(True)   
    app = wx.PySimpleApp(True, "demo1.log")   
    frame = MyFrame()   
    frame.Show(True)   
    app.MainLoop()  
#coding=utf8
#!usr/bin/env python

import wx
class MyFrame(wx.Frame):
    def __init__(self):
        print 'MyFrame.__init__'
        wx.Frame.__init__(self, None, -1, "demo1", size=(300,400))
        panel = wx.Panel(self, -1)
        panel.Bind(wx.EVT_MOTION, self.OnMove)
        wx.StaticText(panel, -1, "Pos:", pos=(10,12))
        self.posCtrl = wx.TextCtrl(panel, -1, "", pos=(40,10))
        
    def OnMove(self, event):
        pos = event.GetPosition()
        self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))
        
        
if __name__ == '__main__':
#    app = wx.PySimpleApp(True)
    app = wx.PySimpleApp(True, "demo1.log")
    frame = MyFrame()
    frame.Show(True)
    app.MainLoop()  
 一つの応用にとって、必要不可欠なのは一つのwx.APP、一つのFrameが必要なので、各アプリケーションは少なくともこの二つを含んでいなければならない。上の例も同じで、次の文で説明します。main_u.ビュー:    ap=wx.PySimpleApp(True,「demo 1.log」)  #一つのアプリから一つ目のパラメータは印刷を出力するかどうか、二つ目のパラメータは出力のファイル名を表し、二つ目のパラメータがNoneであれば、ウィンドウに出力します。    frame=MyFrame()葃起一个Frame    frame.Show(True)  #表示    app.MainLoop()      # 実行権を渡して、カスタマイズされたMyFrameクラスに入ると、まずベースクラスの初期化関数___0026 quot;を呼び出します。init_ひそしてFrameにコントロールパネルを追加して、panelにwx.EVT_をバインドします。MOTIONイベントでは、コールバック関数self.OnMoveが設定されています。引き続きコントロールStatic Textを追加します。引き続きコントロールTextCtrlを追加します。コールバック関数OnMoveでpostionを設定します。
 
import os   
import time   
import datetime   
import wx   
  
class PyOnDemandOutputWindow:   
    """  
    A class that can be used for redirecting Python's stdout and  
    stderr streams.  It will do nothing until something is wrriten to  
    the stream at which point it will create a Frame with a text area  
    and write the text there.  
    """  
    def __init__(self, title = "wxPython: stdout/stderr"):   
        self.frame  = None  
        self.title  = title   
        self.pos    = wx.DefaultPosition   
        self.size   = (450, 300)   
        self.parent = None  
        self.triggers = []   
        self.logfile = None  
  
    def SetParent(self, parent):   
        """Set the window to be used as the popup Frame's parent."""  
        self.parent = parent   
  
  
    def RaiseWhenSeen(self, trigger):   
        """  
        Trigger is a string or list of strings that will cause the  
        output window to be raised when that trigger text is written.  
        """  
        import types   
        if type(trigger) in types.StringTypes:   
            trigger = [trigger]   
        self.triggers = trigger   
           
  
    def CreateOutputWindow(self, st):   
        self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,   
                              style=wx.DEFAULT_FRAME_STYLE)   
        self.text  = wx.TextCtrl(self.frame, -1, "",   
                                 style=wx.TE_MULTILINE|wx.TE_READONLY)   
        self.text.AppendText(st)   
        self.frame.Show(True)   
        self.frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow)   
           
  
    def CreateOutputFile(self, st):   
        self.logfile = file("log.txt", "ab")   
        self.write(st)   
  
    def OnCloseWindow(self, event):   
        if self.frame is not None:   
            self.frame.Destroy()   
        self.frame = None  
        self.text  = None  
        self.parent = None  
  
  
    # These methods provide the file-like output behaviour.   
    def write(self, text):   
        """  
        Create the output window if needed and write the string to it.  
        If not called in the context of the gui thread then uses  
        CallAfter to do the work there.  
        """           
        if self.logfile is None:   
            if not wx.Thread_IsMain():   
                wx.CallAfter(self.CreateOutputFile, text)   
            else:   
                self.CreateOutputFile(text)   
        else:   
            if not wx.Thread_IsMain():   
                wx.CallAfter(self.__write, text)   
            else:   
                self.__write(text)   
  
    def __write(self, text):   
        # helper function for actually writing the text, and   
        # optionally raising the frame if needed   
        dt_now = datetime.datetime.now()   
        dt_now_str = dt_now.strftime("%Y-%m-%d %H:%M:%S")   
           
        self.logfile.write('[%s] %s%s' % (dt_now_str, text, os.linesep))   
  
  
    def close(self):   
        if self.frame is not None:   
            wx.CallAfter(self.frame.Close)   
           
        if self.logfile is not None:   
            self.logfile.flush()   
            self.logfile.close()   
  
  
    def flush(self):   
        if self.logfile is not None:   
            self.logfile.flush()   
     
wxPython        ,         。