• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

Sign in to follow this  

[HOWTO] Program using Python

Recommended Posts

Lechio    15

Lesson #2

In Lesson #1 we've already seen how easy it is to make simple CLI programs that would print messages on the console, and a simple example of a way to display a message on screen using a graphical toolkit. This lesson will explore the graphical toolkits available for python, with special approach to one of the most advanced toolkits available, QT.

Part 1: Joke reader.

In this part we are going to make a simple program that reads a text file and display its contents on screen. We will be making something very (questionably) useful, a joke reader.

post-52106-1228771871.png

  • Download the file attached;
  • Extract it to a directory;
  • Open "joker.py" with your editor.

neowin_joker.zip

The imports.

In this part of the code we import the PyQt4 modules. We are using the "from package.component import *" so we can save on the typing, like it was referred before. If the libraries aren't available then an error message is printed informing about the missing libraries and the program is terminated.

#Import the PyQt4 modules. Exit if not found.
try:
	from PyQt4.Qt import *
	from PyQt4.QtCore import *
	from PyQt4.QtGui import *
except:
	print "Failed to load QT libraries. Please intall PyQt4 first."
	sys.exit(1)

Here we import our jokes module. This module contains an array with our jokes, so we can use and cycle between them later. If the module cannot be imported then the program gets terminated here.

#Import the jokes module. Exit if not found.
try:import jokes
except:
	print "Could not find the jokes."
	sys.exit(1)

Build the widgets.

This is the part where we build our widgets. In this program we are only using a simple text browser and 3 buttons. Those buttons get connected to a function and when the clicked signal is emitted that same function is called. This is explained in the QT manual and should be consulted first before starting to program using QT. Also the "Qt's Main Classes" page is of most importance. In there all the QT components are explained in detail and the way they can be used. It's the API reference page for QT.

class Neowin_Jokster(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)

		print "Starting application"


		self.textBrowser = QTextBrowser(self)
		self.textBrowser.setGeometry(QRect(0,0,511,251))
		self.textBrowser.setObjectName("textBrowser")

		self.buttonPrev=QPushButton(self)
		self.buttonPrev.setText("&Previous")
		self.buttonPrev.setGeometry(QRect(30,255,90,32))

		self.buttonNext=QPushButton(self)
		self.buttonNext.setAutoDefault(1)
		self.buttonNext.setDefault(1)
		self.buttonNext.setText("&Next")
		self.buttonNext.setGeometry(QRect(130,255,65,32))

		self.buttonExit=QPushButton(self)
		self.buttonExit.setText("&Exit")
		self.buttonExit.setGeometry(QRect(430,255,65,32))

		self.connect(self.buttonPrev,SIGNAL("clicked()"),self.prev_joke)
		self.connect(self.buttonNext,SIGNAL("clicked()"),self.next_joke)
		self.connect(self.buttonExit,SIGNAL("clicked()"),self.buttonExit_clicked)

		self.setMinimumSize(QSize(510,290))
		self.setMaximumSize(QSize(510,290))
		try:self.move(QApplication.desktop().width() / 4,QApplication.desktop().height() / 4)
		except:pass


		self.get_jokes()

The jokes.

These two functions are used to cycle between the jokes. They are executed when the "previous" and "next" buttons are pressed, respectively.

	def prev_joke(self):
		"""Previous joke"""
		global curr_joke

		#Cycle between the jokes.
		if curr_joke >= 1:curr_joke -= 1
		else:curr_joke=len(jokes.neowin_jokes)-1
		self.textBrowser.setText( str(jokes.neowin_jokes[curr_joke]) )

	def next_joke(self):
		"""Next joke"""
		global curr_joke

		#Cycle between the jokes.
		if curr_joke <= len(jokes.neowin_jokes)-2:curr_joke += 1
		else:curr_joke=0
		self.textBrowser.setText( str(jokes.neowin_jokes[curr_joke]) )

Quit it.

This function is executed when our "Exit" button is pressed. It's used to exit...

	def buttonExit_clicked(self):
		"""Exit"""
		print "Exit"
		self.close()

Calling and Looping.

This gets executed when the application is invoked. It's used to call our class above so the widget can be created. It also creates a loop so the window executes until it quits. We also set the window title as "neowin.net Jokes Reader". One important part in QT widgets is the "show()". If this wasn't passed to the window nothing would show up.

if __name__ == "__main__":
	app = QApplication(sys.argv)
	f = Neowin_Jokster()
	f.setWindowTitle("neowin.net Jokes Reader")
	f.show()
	sys.exit(app.exec_())

To run this program just open a terminal on the directory where you have your python file and run it by typing on the terminal:

python joker.py

Learning tips:

Add some more widgets to the window.

This completes this part of lesson #2.

_____________________________________________________________

Part 2: Recalculate.

In our previous program we've already seen how to make a simple graphical program, with simple widgets connected to functions that would perform simple tasks. In this tutorial we are going to explore that subject in a bit more detail.

We will be making a calculator (yes another), with a simple graphical interface. 1337 Calculator in a bit over 500 lines of code:

post-52106-1228927456.png

  • Download the file attached;
  • Extract it to a directory;
  • Open "1337_calculator.py" with your editor.

1337_calculator.zip

Declaring globals.

In this part of the code we are declaring our three global variables (palette, pallete2 and var). The variable "var" is in fact a Dictionary, this is one of the most useful datatypes from python and an important one to understand.

palette = palette2 = None

# We start by storing our values inside dictionaries. Dictionaries are nice, they can store a big ammount of variables

# indexed by keys, which allow them to be kept editable to humans (and dolphins too, in a near future).

var={ 'calc_cleared':False, 'calcon_op':False, 'calcurr_op':None, 'calclast_val':None, 'calc_return':int }

Create widgets.

This is our class for creating the window and populating it with all the widgets. Here all the connections from the widget to the functions are made. Analyze the code to see how the individual widgets are connected.

class Leet_Calculator(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)
(...)

Connectors.

These are the small functions to where we have connected our widgets. They get executed when a button in our calculator is pressed. Each one of them will then call our "Abacus" class with a parameter so that the specific action, intended by the key press event, occurs.

#All Clear
	def buttonCE_clicked(self):
(...)

Quit it.

Our "off" button used to exit the program.

#OFF
	def buttonOff_clicked(self):
(...)

Calculations.

This is our calculations class. A class that analyses an "input" and makes the calculations of what to display. Notice how the "__init__" function is written. It's the "__init__" that is responsible for all that will get executed.

#Class used to make our key pressing instructions and calculations

class Abacus:
	def __init__(self,widget,key):
		self.key=key

		if self.key=="CE" or self.key=="C":self.abacusClear(widget)
		elif self.key=="+" or self.key=="-" or self.key=="*" or self.key=="/":self.abacusCalc(widget)
		elif self.key=="=":self.abacusResult(widget)
		else:self.abacusSlide(widget)
(...)

Style.

This function is used to style our buttons, we create some nice palettes so we can then apply those to our buttons. Nothing too advanced here.

#Palette builder
class PaletteBuilder:
(...)

Calling and Looping.

This gets executed when the application is invoked. It's used to call our widget creator class so that the window can be created. It also creates a loop so the window executes until it quits. We also set the window title as "1337 calculator" and call the palette builder.

if __name__ == "__main__":
	app = QApplication(sys.argv)
	PaletteBuilder()
	f =Leet_Calculator()
	f.setWindowTitle("1337 calculator")
	f.show()
	sys.exit(app.exec_())

To run this program just open a terminal on the directory where you have your python file and run it by typing on the terminal:

python 1337_calculator.py

Learning tips:

Make a more advanced calculator.

This completes this part of lesson #2.

Edited by Lechio

Share this post


Link to post
Share on other sites
markjensen    98

I've only ever played with tkinter for GUI work. Might need to try something nicer-looking with qt. (Y)

Share this post


Link to post
Share on other sites
Lechio    15

Thanks Mark. Yes, QT definitely looks better than Tcl/Tk. :)

This lesson will be kept simple, more advanced programming will be looked in next lessons.

Share this post


Link to post
Share on other sites
DomZ    26

With my brief experimentation into python, I used glade and gtk. I found it pretty easy as I didn't have to worry about (too much) coding of the actual interface, you can focus more on the actual functions of the program.

Share this post


Link to post
Share on other sites
mtber    0

How Easy to learn is python?

Share this post


Link to post
Share on other sites
Lechio    15
How Easy to learn is python?

Python is a very easy to learn language.

Some minutes dispensed reading the manual is all it takes to start making basic scripts. Compared to other "object-oriented languages" I personally consider it to be one of the easiest ones to learn. Yet, advanced programming can also be done with python. It's a good language for someone who wants to start programming and, as it does not need to compile, it's also a very good language to implement fast programming solutions.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.