A few weeks back, I posted a couple of examples of trivial (but graphical) Twitter clients. Here's a slightly more featured example, which uses the PyQt library to hook into the powerful cross-platform Qt toolkit from Python.
Here's a screenshot. It shows how many characters you have remaining, and disables posting if the character count is over the limit. Below is the code. To run on a Debian system you'd install the python-qt4 and python-httplib2 packages. I think it is a good example that for simple applications, the Python-Qt framework is pretty nice, though in lines of code, it would probably be about the same in Java (and probably less in JavaFX). Another nice thing is that you can put together the UI with Qt Designer.
Zetcode's PyQt4 tutorial and the official PyQt documentation were indispensable.
#!/usr/bin/python
import sys, urllib, httplib2
from PyQt4 import QtCore, QtGui
class PTwitter(QtGui.QWidget):
max = 140
uid = 'guymac'
pwd = '********'
twitUpdate = 'http://twitter.com/statuses/update.xml'
twitCloser = 'http://twitter.com/account/end_session'
def postTweet(self):
mesg = self.txt.toPlainText()
post = urllib.urlencode({ 'status' : mesg })
try:
http = httplib2.Http()
# override the default (no exceptions, status in response)
http.force_exception_to_status_code = False
http.add_credentials(self.uid, self.pwd)
resp, content = http.request(self.twitUpdate, 'POST', post)
if resp and resp.status == 200:
self.lbl.setText('Twitter updated!')
else:
raise httplib2.HttpLib2Error, 'No response'
except httplib2.HttpLib2Error, ex:
print ex
self.lbl.setText(ex.__str__())
http.request(self.twitCloser)
def updateLabel(self):
len = self.txt.toPlainText().size()
self.lbl.setText('%d char(s) remaining' % (self.max-len))
# disable the post button if chars > max
self.pb1.setEnabled(len <= max)
def __init__(self):
QtGui.QWidget.__init__(self)
# Button to post
self.pb1 = QtGui.QPushButton('Post')
# Button to close
self.pb2 = QtGui.QPushButton('Close')
# TextField for input
self.txt = QtGui.QTextEdit()
# Label to show characters remaining
self.lbl = QtGui.QLabel()
tab = QtGui.QGridLayout()
tab.setSpacing(5)
tab.addWidget(self.txt, 0, 0, 1, 2)
tab.addWidget(self.lbl, 1, 0, 1, 2)
tab.addWidget(self.pb1, 2, 0)
tab.addWidget(self.pb2, 2, 1)
self.setLayout(tab)
self.setWindowTitle('PyQt4 Twitter')
self.updateLabel()
# connect text change to number of chars message
self.connect(self.txt, QtCore.SIGNAL('textChanged()'),
self.updateLabel)
# connect post click to send message
self.connect(self.pb1, QtCore.SIGNAL('clicked()'),
self.postTweet)
# connect close click to quit
self.connect(self.pb2, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('quit()'))
# application
app = QtGui.QApplication(sys.argv)
# window
win = PTwitter()
# display
win.show()
# execute
sys.exit(app.exec_())