Creating an interface for the motif finding script, part 4

motifs, wxPython Comments Off

Last time we checked how to add a menu to our simple frame. Unfortunately, just adding it won’t make the menu useful. In order to do that we need to bind some events to it. As any interface framework, wxPython is governed by events generated by the user, being these events mouse clicks on buttons and menus, objects getting/losing focus, etc. In our case, so far, we evidently need a event called menu event, which will tell the code what path to use when a menu is clicked.

My personal preference for binding an event to menu is to create a separate function to store these procedures, __do_binding. But by using this route we would need to change some code in the menu declaration, and to simplify things we will add the menu binding at the end of the __do_layout function.

And how we create a binding? In order to bind an object/menu to a function that will contain the executed code after the event is fired up, we need the name of the object/menu, the target function and the menu type. We already know the first and the last, we just need the function name then. Remember that we created the menu last time by using (the menu name were changed in the previous entry – it was some old code that got in the way – my mistake)

foreground_menu = filemenu.Append(-1, 'Select foreground file')
background_menu = filemenu.Append(-1, 'Select background file')
...
quitmenu = filemenu.Append(-1, 'Quit')

hence our menu names are foreground_menu, background_menu and quit_menu. Basically a wx.Bind method has this structure

self.Bind(EVENT_TYPE, handler, source)

where the handler is the function and the source is the actual source of the event. Let’s say then we want to use function on_foreground everytime someone clicks on foreground menu, and on_background everytime someone clicks on the background menu. We add a couple of lines to our layout function

self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
self.Bind(wx.EVT_MENU, self.on_background, background_menu)

This will tell the code where to go when these items are clicked. If you start the interface, and error will be generated because we still haven’t created the event handler functions. We should define them

def on_foreground(self, event):
    pass

def on_background(self, event):
    pass

Note that these function receive an event parameter, which is the actual event itself. The pass line means that the function is defined but no actual code has been added, so execution can bypass it and do nothing when the function is called. Our complete code would look like

#!/usr/bin/env python

import wx
import pymot
import fasta

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  'Python Motif Finder', style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, 'Select foreground file')
        background_menu = filemenu.Append(-1, 'Select background file')
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, 'Quit')

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, 'File')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)

    def on_foreground(self, event):
        pass

    def on_background(self, event):
        pass

app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()

Next time we will make good use of the events.

Creating an interface for the motif finding script, part 3

Section 2, motifs, wxPython 2 Comments »

Today we will add some elements to our interface. Looking at the previous screencap it is easy to conclude that our interface needs a lot of work to be ready. First, it has a dark gray background that does not resemble the usual window background (it looks more like a MDI frame). We need to change that. Also, there are no menu bars or menus, or tool bars. It’s pretty bare bones, and not exactly good or useful.

There many ways of customizing the look of a window/frame in wxPython, and two of these methods are adding a panel to the frame or adding the so-called sizers. The latter is a difficult method to master, but powerful and very good to customize objects, look and feels of a window. Addin a panel and subsequently adding objects to it is a more laborious process, but easier to understand. We will start by adding the panel to you __do_layout function (where most of our changes will happen for now).

Basically, only one line is required:

#adding the panel
panel = wx.Panel(self)

That’s it, the wx.Panel method only needs one parameter, where the panel is being added to. The name panel is the one that we will be using to access methods and properties associated with the wx.Panel derivation that we just created.

Adding the menu would require a little bit more code. As its predecessor wxWidgets, wxPython divides the menu in subcategories. The menubar is based on wx.Menubar method, the menu itself (File, Edit, etc) is a wx.Menu wehre each of the entries is added. At the end each menu derived from wx.Menu will be added to the menubar. In order case we have to initialize a menubar

#defines the menubar
menubar = wx.MenuBar()

and then initialize a menu element, which we will call filemenu and will be labeled File

#file menu
filemenu = wx.Menu()

This will only initialize a menu element with the name filemenu, it won’t add anything anywhere. In our case from the start, as we didn’t do any planning on how our interface would look like (no UML, no case studies, nothing!), we need at least three menu items: one to open/set the foreground sequence file, one to open/set the background sequence file and one to quit the application. So what we are going to do is append these items to the filemenu

convertmenu = filemenu.Append(-1, 'Select foreground file')
seqmenu = filemenu.Append(-1, 'Select background file')
sep = filemenu.AppendSeparator()
treenooutmenu = filemenu.Append(-1, 'Quit')

that simple. The first two lines and the last one append the items that open/set files. The -1 parameter is an ID, as we saw previously, when no ID is required for our code we use -1, and the second parameter is the label of that menu item. The menu item sep is a separator, keeping apart the file open/set items and the quit element. One final thing is append the derived wx.Menu to the menubar and set it. We accomplish that by

#appends the menu to the menubar and creates it
menubar.Append(filemenu, 'File')
self.SetMenuBar(menubar)

Line 2 initializes menubar on self, also known as pymotGUI, our main window. Putting everything together our code would look like

#!/usr/bin/env python

import wx
import pymot
import fasta

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):

        wx.Frame.__init__(self, parent, id,  'Python Motif Finder', style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()
#        self.__do_binding()

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, 'Select foreground file')
        background_menu = filemenu.Append(-1, 'Select background file')
        sep = filemenu.AppendSeparator()
        quit_menu = filemenu.Append(-1, 'Quit')

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, 'File')
        self.SetMenuBar(menubar)

#if __name__ == '__main__':
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()

and this would look like the screencap below (on Vista).

gui2

Next time we will work on more elements and activate the menu items.

Creating an interface for the motif finding script, part 2

motifs, wxPython Comments Off

Let’s take a deeper look on the code we started yesterday, piece by piece

class pymot(wx.App):
    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect, filename)

This is the class pymot we derived from wx.App, and this will be the main class for your application. As any other class derived it needs a OnInit or a __init__ function that will take care of initializing things. As usual, we pass self and a redirect parameter, that will tell the application to redirect some output to the command line. We actually don’t need a redirect, but it can be useful in the future to track errors. It’s set to false as we don’t need it now.

class pymotGUI(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  'Python Motif Finder', style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):
        pass

This is the pymotGUI class derived, in this case, from wx.Frame. a wx.Frame is the common window you see in most OS. As above, it needs a OnInit or __init__ function, and here it initializes the window (but does not show it). In the first line of __init__ we have a call to format the window we want to display. The frame method would need these paramaters to customize the window

__init__(self, parent, id, title, pos, size, style, name)

Both title and style are set by default (not that they cannot be changed) in the frame definition, and whe this is called and properly initialized, other parameters can be passed and/or changed. There is a second defined function in the pymotGUI class, __do_layout. This is a personal preference of having all the layout methods for the window grouped in one function. It helps organizing a bit the code and easier to browse and correct it if needed.

Most of the main part of the script could be moved to the wx.App class derivation, but for now, we can keep it there.

app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()

The first line initializes the application, the second calls and initializes the frame. The method Show makes the window to be displayed. MainLoop we saw last time.

The skeleton of a wxPython script and application is very simple. Now we need to populate our window, create menus, buttons, and specially events. Next time we will include a menu on the form and check how events are linked to elements.

Creating an interface for the motif finding script, part 1

motifs, wxPython Comments Off

And we are back. After much ado about real life, I am able to “restart” this blog and probably with a good frequency of posts. Last time we saw the final product of our motif finding series. We ended up creating a very elegant script in Python that efficiently counts words in FASTA sequences and then using a basic statistical method, calculates the significance of each word and output the overrepresented ones.

Our script used a little bit less than 50 lines, and if you include the imported fasta module, it won’t top 100. But the number of lines is not important. The efficiency, clarity and speed are key here. At the same time, running a script from the command line is not something everyone is used to do. In order to add more visibility to our simple script, why not including a GUI? With a visual interface, more people can use our script, in different systems. Sounds great.

Python has many options of GUI frameworks, some more cross-platform that others. In the end finding the right framework is more a matter of taste, or availability. My personal experience with wxWidgets lead me to start developing in wxPython, and for me this was a natural choice. But there are many other GUI frameworks for Python, each one providing more or less integration and portability (you can “choose” you own here).

So, let’s create a skeleton for our GUI. First step is to install wxPython. Packages for Windows are available from their website, RPMs for Linux and DMG for Macs (I’m quite sure OS X Leopard comes with wxPython by default, just test importing it). After installing it, start Python and check if everything is in place

import wx
wx.__version__

On my machine, I get no errors and the version is 2.8.9.1 (you don’t need the latest version to create the GUI). Everything seems to be fine. A wxPython script has the same format as any Python script, the only difference is that its output is not directed to the prompt or a file. The script’s product will be the screen, so in most cases the output and program usage will depend on the user’s interaction with objects on the screen. Like any other graphical interface. A very simple script would look like

#!/usr/bin/env python

import wx

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  'Python Motif Finder', style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):
        pass

app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()

Usually a wxPython interface has three parts in its script: a class for the window/frame/dialog, a class for the application and a initialization routine. All wxPython applications, and scripts, need to derive an wx.App class and initialize it (on OnInit or on __init__ functions), i.e. create the window, begin the program, etc. Another class, derived from wx.Frame in this case, will build the window/frame/dialog per se and will also contain initialization for the window, objects, events, etc. The last part is the main script where the application is started, by calling the derived class, the window is also called and shown. The last line is the MainLoop, present in every wxPython script, and it is the main line of the script, the heart of the application. MainLoop processes all the events and manages how the objects interact by receiving and dispatching such events.

The script above could have been created differently, some lines of it omitted and there is also no need to derive an specific class for the frame. But this way it is easier to get a grasp of the script as it will need to be enlarged so accomodates the objects and maybe a couple of extra windows and dialogs. Running the above script will generate the window below

First screencap of our GUI

very simple and barebones. Next will explore the script above, include some extra elements and learn a little bit more of wxPython.

Design by j david macor.com.Original WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in