Browse > Home

| Subcribe via RSS

Replacer - My First Python GUI

December 18th, 2008 | No Comments | Posted in Programming, Python
Replacer

Replacer

I finally got around to digging into some GUI programming with Python. I had been working on a text-based turn-based command line game and decided to take a break from that in order to pick up some GUI related knowledge. I opted for something simple and wound up with this search and replace program. There’s not much to it. Enter the text to change, the string to look for, the string to replace it with, and press the button to view the altered text.

I have to admit that it took me a while to write this bit of code. I’m not sure how much time I spent looking at all sorts of web sites for examples, different GUI editors, and other information. Finally I decided that I’d had enough of looking and needed to actually start making something. I already had wxPython installed in order to run SPE, so I opted to use the wxWidgets for my GUI program.

Now maybe this is just my lack of Python knowledge speaking, but I had one heck of a time finding examples and tutorials that really made it clear to me what went into even a simple graphical interface. Maybe I was looking in the wrong places for help. I don’t know. I was pretty happy when I found a good snippet of code on a forum, so that is what I used as the basis for what I wrote.


#!/usr/bin/env python

#----------------------------------------------------------------------
# Name:         replacer.py
# Purpose:      A simple program for learning the basics of some
#               GUI programming with wxPython. This program is
#               basically a self-contained search and replace tool.
# Dependencies: wxPython
#----------------------------------------------------------------------

import wx

class ReplacerPanel(wx.Panel):

	def __init__(self, parent, id):
		wx.Panel.__init__(self, parent, id)

		# Create the first static text label (staticText1)
		# and text control (textarea1).
		# This is a multiline text area where the user inputs
		# the string that will be the subject of the search/replace.
		self.staticText1 = wx.StaticText(self, label="Input Text Here:",
			pos=wx.Point(10, 15))
		self.textarea1 = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE,
			pos=wx.Point(10, 30), size=wx.Size(300,100), name="input")
		self.textarea1.SetBackgroundColour((255,255,255))

		# Create the second static text label (staticText2)
		# and text control (textarea2).
		# This is a multiline text area where the post-replace
		# output is displayed.
		self.staticText2 = wx.StaticText(self, label="Replaced Text:",
			pos=wx.Point(10, 205))
		self.textarea2 = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE,
			pos=wx.Point(10, 220), size=wx.Size(300,100), name="output")
		self.textarea2.SetBackgroundColour((220,220,220))

		# Create the third static text label (staticText3)
		# and text control (textbox1).
		# This is a textbox where the user will input the text
		# to be replaced.
		self.staticText3 = wx.StaticText(self, label="Text To Replace:",
			pos=wx.Point(10, 150))
		self.textbox1 = wx.TextCtrl(self, 1, pos=wx.Point(10, 165),
			size=wx.Size(125,-1), name="toReplace")

		# Create the fourth static text label (staticText4)
		# and text control (textbox2).
		# This textbox is for the string that will replace
		# any matches of the value in textbox1.
		self.staticText4 = wx.StaticText(self, label="Replace With:",
			pos=wx.Point(185, 150))
		self.textbox2 = wx.TextCtrl(self, 1, pos=wx.Point(185, 165),
			size=wx.Size(125,-1), name="toReplaceWith")

		# Create a button with an event binding that triggers
		# the actual search and replace process.
		self.button1 = wx.Button(self, id=-1, label="Do It!",
			pos=wx.Point(325, 30))
		self.button1.Bind(wx.EVT_BUTTON, self.button1Click, self.button1)

	# This is the function that is executed when the button (button1) is
	# pressed.
	def button1Click(self, event):
		inputText = self.textarea1.GetValue()
		inputToReplace = self.textbox1.GetValue()
		inputReplaceWith = self.textbox2.GetValue()
		outputText = inputText.replace(inputToReplace, inputReplaceWith)
		self.textarea2.SetValue(outputText)

# Calls on the ReplacerPanel class to put the GUI together.
def main():
	app = wx.PySimpleApp()
	frame = wx.Frame(None, -1, "Replacer", size = (420, 375))
	ReplacerPanel(frame,-1)
	frame.Show(True)
	app.MainLoop()

# Tell the computer to run the main() function.
if __name__ == '__main__':
    main()
Tags: , , , ,

Simple Text Based Calculator

November 30th, 2008 | No Comments | Posted in Uncategorized

Last night I wrote my first Python program. Initially I had decided to try creating a calculator that included a GUI, but after putting together the interface in Boa Constructor (which gave me a chance to take a peek at another Python editor) and finding myself somewhat lost as far as what to do next I opted for something less complex. The whole goal was to make something that would allow me to learn some of the basics of Python. Apparently I was thinking a little too big when I was aiming to include the GUI as part of that goal. Nevertheless, I did learn quite a bit in going with the text based version instead.


# Simple Text Based Calculator
#
# The functionality is very simple. It prompts for three things:
#	1. The first number.
#	2. The type of math operation to be used.
#	3. The second number.
# Once the three pieces of information have been input by the user,
# then the mathematical operation is executed and the answer is output.

# This function checks to see if the parameter is a valid float type.
def floatCheck(testString):
	testOk = 1
	try:
		num = float(testString)
	except ValueError:
		testOk = 0
	return testOk

# Output a short description of the program and how to use it.
print """
This is a simple text based calculator.

Mathmatical operations available are:
Addition, Subtraction, Multiplication, and Division.

Follow the directions at the prompt or type quit to exit.
"""

# Start a loop that processes the user's input or allows them to quit.
while True:

	# Prompt the user for the first number.
	firstNumber = raw_input("\nEnter the first number for the operation: ")
	# If the user enters "quit" then "Goodbye is output", the loop is ended,
	# and the program stops.
	if firstNumber == 'quit':
		print "\nGoodbye."
		break
	# Prompt the user for the type of mathematical operation to use.
	opType = raw_input("\nEnter the operation type (+, -, *, /): ")
	if opType == 'quit':
		print "\nGoodbye."
		break
	# Prompt the user for the second number.
	secondNumber = raw_input("\nEnter the second number for the operation: ")
	if secondNumber == 'quit':
		print "\nGoodbye."
		break

	# Verify that the first and second numbers are valid. If not then
	# output the appropriate message. If they are valid then continue
	# to a tree that executes the appropriate mathematical operation.
	if floatCheck(firstNumber) == 0:
		print "\nERROR: The first number was invalid."
	elif floatCheck(secondNumber) == 0:
		print "\nERROR: The second number was invalid."
	else:
		# Now that the first and second number have been verified to indeed
		# be numbers, convert them to the float data type.
		firstNumber = float(firstNumber)
		secondNumber = float(secondNumber)
		if opType == '+':
			# Addition
			theAnswer = firstNumber + secondNumber
			print "\nThe answer is: ", theAnswer
		elif opType == '-':
			# Subtraction
			theAnswer = firstNumber - secondNumber
			print "\nThe answer is: ", theAnswer
		elif opType == '*':
			# Multiplication
			theAnswer = firstNumber * secondNumber
			print "\nThe answer is: ", theAnswer
		elif opType == '/':
			# Division
			# To avoid division by zero issues, check the value of the
			# second number. If it is 0, then output an error.
			if secondNumber == 0:
				print "ERROR: Cannot perform division by zero."
			else:
				theAnswer = firstNumber / secondNumber
				print "\nThe answer is: ", theAnswer
		else:
			# Output a message when the operation type entered was not
			# one of those that is expected.
			print "\nERROR: An invalid operation type was entered."
Tags: , ,

Which Tools To Use For Python Development

November 30th, 2008 | No Comments | Posted in Programming, Python

Over the course of the last couple days I’d been thinking that my first little project with Python would be a very basic calculator application that included a graphical interface. This goal lead me to scouring the internet to find the tools I would need to be able to create the simple application. As with any other language, there are plenty of options available, so I wound up trying a few of them myself. I still am not completely decided on which ones to use, but I’m comfortable with the ones I played with so far.

The IDE/editor that I’ve found myself most comfortable with is Stani’s Python Editor (SPE for short). It’s full of features, seems easy to figure out, and has given me no problems so far. Now, perhaps as I become more savvy with Python and my needs from a development environment grow, I will find myself needing more from the IDE, but at the moment SPE looks like the right choice and, from what I have gathered by reading a variety of websites, quite a few other Python programmers feel the same way.

SPE Home Page: http://pythonide.blogspot.com/
SPE Downloads: http://developer.berlios.de/project/showfiles.php?group_id=4161
Good info about the SPE download and install process: http://blog.chomperstomp.com/?p=165

Tags: , ,

Starting With Python

November 29th, 2008 | No Comments | Posted in Programming, Python

I’ve been doing programming of some kind since I was in junior high. Most of my experience has been with web applications using ASP, vbScript, JavaScript, and HTML. With the way the economy and my current employer is doing, I’ve decided to finally (after putting it off for far too long) expand my horizons by starting to learn Python.

My decision to try out Python was made based on a few things.

First, I wanted to do something that wasn’t platform specific like vbScript and ASP. Even though I spend all of my time working in a Windows environment both at work and at home, the idea that something I create could run on another OS is appealing, not to mention the fact that it will hopefully open some doors down the road when I am exploring employment opportunities.

The second factor in my decision was that although I have spent a long time programming for web applications, I want to do something that will allow me to get away from just doing that. One might point out that vbScript can be used to do more than just web applications, which is true, but then there’s the whole one OS issue. Python is far more flexible as it can be used for web development, application development, and doesn’t require a specific OS. That sounds good to me.

The other reason I’m going with Python is because the code examples I’ve looked at so far made sense to me without much difficulty. I also spent a few hours tinkering with a little program and found myself having little trouble figuring out solutions for the mistakes I was making. I remember feeling the same way when I started learning vbScript.

Time to dig in!

Tags: , , , , ,
  • Tags

      ASP Calculator gui HTML IDE JavaScript Learning Programming Python replacer SPE vbScript wxpython

      WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.

  • Recent Posts

  • Categories

  • Archives

  • Links

  • Meta