pythonで複数OSに対応したGUIプログラミングをする


ふとPythonGUIプログラミングを行いたいと思ったので、様々なOSで実行する事が可能と言われているGUI toolkit 「wxPython」を使って色々と試してみました。結果としては”感動”の一言です。
職場と自宅で作業する環境が違う自分としてはとても助かります。これは色々と捗るぞ!

サンプルコード

非常にシンプルなテキストエディタのコードです。このサンプルコードはwxPythonのチュートリアルからの転記です。

import os
import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(200,100))
        self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        self.CreateStatusBar() # A StatusBar in the bottom of the window

        # Setting up the menu.
        filemenu= wx.Menu()

        # wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets.
        menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
        menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")

        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.

        # Set events.
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)

        self.Show(True)

    def OnAbout(self,e):
        # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
        dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK)
        dlg.ShowModal() # Show it
        dlg.Destroy() # finally destroy it when finished.

    def OnExit(self,e):
        self.Close(True)  # Close the frame.

app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()

Mac OSX(Snow Leopard) - Carbon

実行画面


環境

python26はSnow Leopardで標準インストールされるMacPython2.6.1です。

実行時の注意点
macbook:~ ox$ arch -i386 python gui.py 

Snow Leopardに標準でインストールされているPythonは64bitで動作をしています。
Defaultsを編集する事により32bitで動作させる事が可能という情報がmanや色々なブログにあったのですが、どうやっても64bitモードで動作をしてしまいwxPythonのimport時にエラーが出てしまいました。それから色々調べた所、上記のように起動時に$ arch -i386と指定する事によって32bitモードでPythonの実行をする事ができました。

Mac OSX(Snow Leopard) - gtk

実行画面


環境

gtk版はMacPortsを使用して構築した環境です。インストールコマンドは以下。
インストールに合計3時間位かかるので暇つぶしを用意しておいた方が好ましいです。

macbook:~ox$ sudo port install python26
macbook:~ox$ sudo port install py26-wxpython

Ubuntu 10.04 LTS - Lucid Lynx

実行画面


環境

Luxid Lynxは最初からPython2.6.5がインストールされていたため、python-wxgtkをapt-getでインストールするだけで実行できました。コマンドは以下。

ox@ubuntu-vm:~$sudo apt-get install python-wxgtk2.6

Windows XP

実行画面


環境

上の2つをインストールするだけで何も悩む事なく動きました。


なんだかんだでMacPythonで実行するのに少々ハマりましたが、これで様々な環境で実行できるプログラムが作れそうです。