tags:

views:

808

answers:

3

The SWT-Gui looks very nice. Is there an easy way to use it in Jython ?

+10  A: 

Given that you can use all Java classes from within Jython, it is also possible to use SWT.

For the example, adapted from an SWT snippet, make sure you have the SWT jar on your CLASSPATH:

import org.eclipse.swt as swt
import org.eclipse.swt.widgets as widgets
import org.eclipse.swt.layout as layout

result = None

display = widgets.Display()

shell = widgets.Shell(display)
shell.pack()
shell.open()

dialog = widgets.Shell(shell, swt.SWT.DIALOG_TRIM | swt.SWT.APPLICATION_MODAL)
dialog.setLayout(layout.RowLayout())

ok = widgets.Button(dialog, swt.SWT.PUSH)
ok.setText ("OK")
cancel = widgets.Button(dialog, swt.SWT.PUSH);
cancel.setText("Cancel");

class MyListener(widgets.Listener):
    def handleEvent(self, event):
        global result
        result = event.widget == ok
        dialog.close()

listener = MyListener()
ok.addListener(swt.SWT.Selection, listener)
cancel.addListener(swt.SWT.Selection, listener)

dialog.pack()
dialog.open()
while not dialog.isDisposed():
    if not display.readAndDispatch():
        display.sleep ()
print "Result:", result
display.dispose()
Torsten Marek
Thank you Torsten, it looks very easy. (Sorry cannot upvote now)
Natascha
Ah, it won't take long until you can do that.
Torsten Marek
+5  A: 

Actually, there is no need for a special module. This talk by Sean McGrath contains a simple example of a Jython/SWT GUI.

Slide 11 of the talk begins with:

"""
Simple SWT Example
Sean McGrath
"""
from org.eclipse.swt.events import *
from org.eclipse.swt.graphics import *
from org.eclipse.swt.layout import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout.GridData import *
from org.eclipse.swt import *

It shows that SWT is directly usable from Jython. The full example is right there at Sean's site.

gimel
to gimel : Thank you !
Natascha
+6  A: 

Jython has a few other niceties that makes the code cleaner.

Jython automagically translates getters & setters into public properties so that

ok.setText ("OK")

becomes simply

ok.text = 'OK'

You can then supply them as named arguments to the constructor. Jython also handles creating listener objects for your event handlers:

def handleEvent(self, event):
    global result
    result = event.widget == ok
    dialog.close()

ok = widgets.Button(dialog, swt.SWT.PUSH
        text='OK',
        widgetSelected=handleEvent)
cancel = widgets.Button(dialog, swt.SWT.PUSH
        text='Cancel',
        widgetSelected=handleEvent)
Peter Gibson
The "ok.text = 'Ok'" form is more idiomatic Jython (that is, it is more Pythonic -- it looks and feels more like Python code)
Frank Wierzbicki