Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming > Application Programming

Reply
 
LinkBack Thread Tools
Old 06-09-08   #1 (permalink)
The Game
 
lattyware's Avatar
 
intel nvidia

Join Date: Feb 2007
Location: In A Faraday Cage
Posts: 2,674

Rep: 280 lattyware is a proven memberlattyware is a proven memberlattyware is a proven member
Unique Rep: 206
Folding Team Rank: 538
Hardware Reviews: 1
Trader Rating: 0
Default Tutorial: Using Python/Glade to create a simple GUI application.

Writing a GUI app with Python & Glade

Edit: Please do check out the video screencast of this tutorial.

Here is what is to be created:



This tutorial will assume a basic knowledge of programming in general, and an understanding of Python. You don't even really need that, but if you don't know python well, you might need to look some stuff up, but google is your friend. This tutorial also assumes you are running Linux. I don't know about glade on Windows, so you'd have to check that out yourself.
You will also need to install python and glade.

Writing a GUI application to do a task may seem like a difficult job, but in fact, it can be very simple. Python is the language of choice for me, it's simple and fast to develop in, with a fair amount of power behind it.

First of all, we need an idea of what to do. Let's do something very basic to begin with, a program to add two numbers, and display an output. We'll start by creating a simple CLI app, which we'll convert.

tutCLI.py:
Code:
class adder:

	result = 0
	
	def __init__( self, number1, number2 ):
		self.result = int( number1 ) + int( number2 )
		
	def giveResult( self ):
		return str(self.result)
	
endIt = False		
while ( endIt == False ):
	print "Please input two intergers you wish to add: "
	number1 = raw_input( "Enter the first number: " )
	number2 = raw_input( "Enter the second number: " )
	try:
		thistime = adder( number1, number2 )
	except ValueError:
		print "Sorry, one of your values was not a valid integer."
		continue
	print "Your result is: " + thistime.giveResult()
	goagain = raw_input( "Do you want to eXit or go again? ('X' to eXit, anything else to continue): " )
	if ( goagain == "x" or goagain == "X" ):
		endIt = True
This is a simple python script to get the input. The class 'adder' does the actual addition. Taking two inputs in the constructor (__init__), and then adding the two, and storing the result in the 'result' member.
The rest is the stuff that makes our CLI work. It gives the user instructions, takes some input, then it adds the numbers (note this is in a try/except to see if an exception was thrown. This is so we don't throw ugly errors to the user if they input something which is not an integer. It then prints the result, and asks if the user wants to go again, all pretty self-explanetory.

Now we need to create a GUI for this. Open up glade.
Press the 'New Window' button on the left, under 'Toplevels'. This will give you an empty window.



Before we begin, I will make note that glade works in a way that web developers will be used to, by using relative positioning, and splitting the area to arrange things, not by absolute values.

You will need to create a vertical box with 3 items. This splits our window into three segments. The top will be instructions, the bottom buttons and information, the middle the entry areas.



Create a label, and put it up top, don't worry about the text at the moment. Next create a table 2 wide and 3 down in the middle, and finally a horizontal box with 2 items at the bottom.



In the middle, put a label in each as the three left-hand items, and a Text Entry as the right hand portion.



In the bottom, make another 2-item horizontal box in the bottom-left hand corner. Now add an image and a label to the this box. On the right of the main box add a two-item button box in the right hand slot. Add a button to each of these slots.



Add some appropriate text to the top label, and Number 1, Number 2, and Result to the labels on the left. This can all be done in the properties area on the right of your screen. Change your image in the bottom left hand corner to 'Stock' and then choose the stock image 'Warning'. Make the label next to it a warning (like "Sorry, one of your values was not a valid integer." in our CLI). For the two buttons, choose 'Stock' for both, and make one 'gtk-quit' and one 'gtk-add' - for obvious reasons.



OK, so we have everything set up, but it looks decidedly wonky and out of proportion. To counter this, you need to edit the way the items expand. Select the first Text Area, and go into 'packing'. Turn off the vertical 'Expand' option. Repeat this for all of the Text Areas and labels. You will need to go through your items forcing them to expand or not until it looks correct. (Only items in tables have individual horizontal and vertical expand options. For example, the button box should have 'expand' off.) Remember, you can use the tree view to the right to select items, so go through each one one-by-one and check it expanded and not, and see which works, you'll soon get the hang of what needs to be expanded to make the GUI function correctly.



You should end up with something like this:



Once you have, we still have a little to do in glade. Choose your Window (probably 'window1' in your treeview) and go to the 'General' tab in the properties window. Change the name to something more suitible - 'windowMain' is what I'll use. Set Window Title to something you want the user to see ("Latty's Amazing Adder!" in my case.). Next go to the signals tab, and open 'GtkObject' - and click on "destroy" - the dropdown menu under 'handler' - then choose 'on_windowMain_destroy' - This is the event that the GUI will give your application to say the user has tried to quite the application (by clicking on the close icon). Make sure to click somewhere else so it goes out of edit mode before doing anything else, otherwise it'll not save that signal.



Repeat this process for everything you will need to access, changing the names of the entries to something appropriate (these don't need any signals), changing the name of the bottom left hand hbox which contains your warning to something more apt, and changing the names of the two buttons then creating 'clicked' signals for both of them.

Almost there! Finally, we need to make a few small edits. Select the hbox which contains your warning (which should not be renamed something, hboxWarning in my case) - then set 'visible' to false. We don't want this warning shown to begin with. You need to do the opposite for the main window, which you do want visible, so make sure it is. You will also want to turn 'sensitive' on the result Text Entry (under 'Common') to be false - this is for the user to see the result, they don't need to edit it. This will 'grey-out' the box (allthough not in glade, for some reason. You also need to go to the button box containing your two buttons and set 'pack type' under 'packing' to end, so it doesn't move around when the warning appears and disappears.



There! Done with the GUI. Save it in the same folder as where you will develop your app. "main.glade" in my case.

OK, let's begin with our GUI script. First of all, we need to import the libraries we will need.

Code:
import sys
try:  
	import pygtk  
	pygtk.require("2.0")  
except:  
	pass  
try:  
	import gtk  
	import gtk.glade  
except:  
	print("GTK Not Availible")
	sys.exit(1)
The sys library is there purely to allow us to call 'sys.exit' - used to exit the application. The rest is to import the GTK, our graphical library. It should all make sense.
Next we need to have our adder class again, this is unchanged from our original application (the wonders of object orientation, kids):

Code:
class adder:

	result = 0
	
	def __init__( self, number1, number2 ):
		self.result = int( number1 ) + int( number2 )
		
	def giveResult( self ):
		return str(self.result)
Now, here comes the juicy bit, the GUI class.

Code:
class leeroyjenkins:

	wTree = None

	def __init__( self ):
		self.wTree = gtk.glade.XML( "main.glade" )
		
		dic = { 
			"on_buttonQuit_clicked" : self.quit,
			"on_buttonAdd_clicked" : self.add,
			"on_windowMain_destroy" : self.quit,
		}
		
		self.wTree.signal_autoconnect( dic )
		
		gtk.main()

	def add(self, widget):
		try:
			thistime = adder( self.wTree.get_widget("entryNumber1").get_text(), self.wTree.get_widget("entryNumber2").get_text() )
		except ValueError:
			self.wTree.get_widget("hboxWarning").show()
			self.wTree.get_widget("entryResult").set_text("ERROR")
			return 0
		self.wTree.get_widget("hboxWarning").hide()
		self.wTree.get_widget("entryResult").set_text(thistime.giveResult())
	
	def quit(self, widget):
		sys.exit(0)
Basically, it loads the widget tree from your glade file, and then creates a list of signals and what methods they point to. In our case, closing the window and clicking quit both make it quit (a member function which is pretty obvious), and clicking add calls our add member function.

The gtk.main() function just makes a loop which will display the GUI, and handle any signals as you have told it to.

Notice members called by signals need a 'widget' parameter. This is the widget that set off that signal. We don't need this, but you might in another case. Our add function should look very familiar, and should be pretty self explanetory.

Alright, that's it! Here is the end result in full:

Code:
import sys
try:  
	import pygtk  
	pygtk.require("2.0")  
except:  
	pass  
try:  
	import gtk  
	import gtk.glade  
except:  
	print("GTK Not Availible")
	sys.exit(1)

class adder:

	result = 0
	
	def __init__( self, number1, number2 ):
		self.result = int( number1 ) + int( number2 )
		
	def giveResult( self ):
		return str(self.result)
		
class leeroyjenkins:

	wTree = None

	def __init__( self ):
		self.wTree = gtk.glade.XML( "main.glade" )
		
		dic = { 
			"on_buttonQuit_clicked" : self.quit,
			"on_buttonAdd_clicked" : self.add,
			"on_windowMain_destroy" : self.quit,
		}
		
		self.wTree.signal_autoconnect( dic )
		
		gtk.main()

	def add(self, widget):
		try:
			thistime = adder( self.wTree.get_widget("entryNumber1").get_text(), self.wTree.get_widget("entryNumber2").get_text() )
		except ValueError:
			self.wTree.get_widget("hboxWarning").show()
			self.wTree.get_widget("entryResult").set_text("ERROR")
			return 0
		self.wTree.get_widget("hboxWarning").hide()
		self.wTree.get_widget("entryResult").set_text(thistime.giveResult())
	
	def quit(self, widget):
		sys.exit(0)
		
letsdothis = leeroyjenkins()
Note the last line which creates an object of our GUI class, this makes the program actually begin.




There we have it, a simple GUI app with Python and Glade. It's not that hard to do. This example, of course, may seem like a lot of work for little result, as the resulting application is not that useful, but what you have learnt here can easily be applied to other things.

If you want to see a fully functional app written in python/glade, check out simpleconf. This was written for OCNix and is made in exactly the same way as is outlined here. You should be able to see how it functions. The source code is right there, so take a look.

Edit: Forgot to mention, there is a reason to use the stock buttons wherever possible. They are automatically translated to the language the user is currently using, and change icon with the theme the user is using, so it always fits in.

Attached is the full source to everything.
Attached Files
File Type: zip tutorial.zip (2.2 KB, 410 views)
__________________
Lattyware | Main (Sig) Rig: gBOX42 | Lan Rig: gLAN42
Never been convinced by Linux? Here is a challenge. | Using LVM
Scratched Disc? | Guide To LAN Parties | Writing a GUI application in Python/Glade
Etching an image into your case. | Wireless Access Points: Easy wireless networking.
A Member Of The OCN Anime/Manga Club

"I disapprove of what you say, but I will defend to the death your right to say it." --Evelyn Beatrice Hall

System: gBOX42
CPU
Core 2 Duo E6600 @ 3.51GHz
Motherboard
Asus P5B Deluxe/WiFi-AP
Memory
2 x OCZ DDR2 Platinum 1Gb PC6400 C4
Graphics Card
256MB MSI 8600GTS
Hard Drive
2x 1TB SATA, 2 x 500GB SATA
Sound Card
Creative Soundblaster Audigy SE
Power Supply
SEASONIC S12-600
Case
CoolerMaster Cosmos
CPU cooling
XSPC X2O Delta CPU Waterblock V2
GPU cooling
D-Tek FuZion GFX Block
OS
Arch Linux x64
Monitor
Dell 2407WFP, Dell E248WFP

Last edited by lattyware : 09-27-09 at 04:13 AM
lattyware is offline I fold for Overclock.net Overclocked Account lattyware's Gallery   Reply With Quote
Old 07-06-08   #2 (permalink)
New to Overclock.net
 
biatchi's Avatar
 
intel ati

Join Date: Mar 2006
Location: 53°45′N 2°42′
Posts: 3,203

Rep: 183 biatchi is acknowledged by manybiatchi is acknowledged by many
Unique Rep: 126
FAQs Submitted: 1
Trader Rating: 1
Default

Looks like a sweet guide Latty! When I've got some time i'll give it a proper read, It might even make me learn how to code in Python

Can't believe it's been here 3 weeks and this is the first comment.

Nice job rep+ and 5 stars
__________________
Basically Random Idiotic Terrible Insanely Stupid Humour

ace8uk - I wish George Michael would suck me.
ace8uk - Well, I have to say... I do love the little kiddies.
meticadpa - I look like a paedophile with a moustache.
kerbitroy - I look like a paedophile with or without a moustache


System: Pronbox ( . Y . )
CPU
Q6600 G0 Slacr 3.24 ~ 1.3625v
Motherboard
DS3R Pencil modded-ish
Memory
2 x 2 XMS2 ~ 900 5,5,5,15@1.90v
Graphics Card
Power Color Hd4870 512Mb ~ 800 1125
Hard Drive
1TB Sammy Spinpoint F1
Sound Card
Onboard :( > Kef 103.2 reference circa 1979
Power Supply
PC P&C Silencer 750w
Case
Crappy
CPU cooling
TRUE with Nidec Beta V TA450DC
GPU cooling
Stock PowerColor
OS
W7 RTM
Monitor
Viewsonic VA1912W
biatchi is offline biatchi's Gallery   Reply With Quote
Old 07-09-08   #3 (permalink)
The Game
 
lattyware's Avatar
 
intel nvidia

Join Date: Feb 2007
Location: In A Faraday Cage
Posts: 2,674

Rep: 280 lattyware is a proven memberlattyware is a proven memberlattyware is a proven member
Unique Rep: 206
Folding Team Rank: 538
Hardware Reviews: 1
Trader Rating: 0
Default

Cheers. I just presumed there were not that many people interested in Linux and Programming here, by the looks of it. Glad to know it's going to use :P
__________________
Lattyware | Main (Sig) Rig: gBOX42 | Lan Rig: gLAN42
Never been convinced by Linux? Here is a challenge. | Using LVM
Scratched Disc? | Guide To LAN Parties | Writing a GUI application in Python/Glade
Etching an image into your case. | Wireless Access Points: Easy wireless networking.
A Member Of The OCN Anime/Manga Club

"I disapprove of what you say, but I will defend to the death your right to say it." --Evelyn Beatrice Hall

System: gBOX42
CPU
Core 2 Duo E6600 @ 3.51GHz
Motherboard
Asus P5B Deluxe/WiFi-AP
Memory
2 x OCZ DDR2 Platinum 1Gb PC6400 C4
Graphics Card
256MB MSI 8600GTS
Hard Drive
2x 1TB SATA, 2 x 500GB SATA
Sound Card
Creative Soundblaster Audigy SE
Power Supply
SEASONIC S12-600
Case
CoolerMaster Cosmos
CPU cooling
XSPC X2O Delta CPU Waterblock V2
GPU cooling
D-Tek FuZion GFX Block
OS
Arch Linux x64
Monitor
Dell 2407WFP, Dell E248WFP
lattyware is offline I fold for Overclock.net Overclocked Account lattyware's Gallery   Reply With Quote
Old 08-09-08   #4 (permalink)
RAM Fan
 
DjQurt's Avatar
 
intel

Join Date: Jul 2007
Location: Colorado
Posts: 2,351

Rep: 82 DjQurt is acknowledged by some
Unique Rep: 77
Trader Rating: 6
Default

latty you should help me with learning python i got some question i cant get anyone to anwser!
__________________
Quote:
Originally Posted by falven View Post
What if i was gay???

Visit my city!
Increase my industry
Increase my traffic

System: laptop
CPU
Pentium dual core 1.86ghz
Motherboard
dell
Memory
2x1gb's
Graphics Card
x3100
Hard Drive
250gb sata
Power Supply
brick
Case
dell laptop case
CPU cooling
stock
GPU cooling
stock
OS
Windows 7
Monitor
15.4in
DjQurt is offline   Reply With Quote
Old 08-25-08   #5 (permalink)
PC Gamer
 
-Darkness-'s Avatar
 
Join Date: Apr 2008
Location: Far, far away.
Posts: 63

Rep: 4 -Darkness- Unknown
Unique Rep: 3
Trader Rating: 0
Default

Can't VB do this?

I know python is awesome...but what makes it so awesome?
__________________
Quote:
Originally Posted by Base64
SWYgeW91IGNhbiByZWFkIHRoaXMsIHlvdSBhcmUgb3Zlci1lZH VjYXRlZC4=

Code:
If bored = true then
webbrowser1.browse ("www.overclock.net")
      End If
-Darkness- is offline   Reply With Quote
Old 08-26-08   #6 (permalink)
The Game
 
lattyware's Avatar
 
intel nvidia

Join Date: Feb 2007
Location: In A Faraday Cage
Posts: 2,674

Rep: 280 lattyware is a proven memberlattyware is a proven memberlattyware is a proven member
Unique Rep: 206
Folding Team Rank: 538
Hardware Reviews: 1
Trader Rating: 0
Default

Because a) The GTK & Python are cross-platform, b) VB is a proprietry format controlled by M$, c) Python is a much nicer language, with more power.

What makes it awesome? Try writing in it.
__________________
Lattyware | Main (Sig) Rig: gBOX42 | Lan Rig: gLAN42
Never been convinced by Linux? Here is a challenge. | Using LVM
Scratched Disc? | Guide To LAN Parties | Writing a GUI application in Python/Glade
Etching an image into your case. | Wireless Access Points: Easy wireless networking.
A Member Of The OCN Anime/Manga Club

"I disapprove of what you say, but I will defend to the death your right to say it." --Evelyn Beatrice Hall

System: gBOX42
CPU
Core 2 Duo E6600 @ 3.51GHz
Motherboard
Asus P5B Deluxe/WiFi-AP
Memory
2 x OCZ DDR2 Platinum 1Gb PC6400 C4
Graphics Card
256MB MSI 8600GTS
Hard Drive
2x 1TB SATA, 2 x 500GB SATA
Sound Card
Creative Soundblaster Audigy SE
Power Supply
SEASONIC S12-600
Case
CoolerMaster Cosmos
CPU cooling
XSPC X2O Delta CPU Waterblock V2
GPU cooling
D-Tek FuZion GFX Block
OS
Arch Linux x64
Monitor
Dell 2407WFP, Dell E248WFP
lattyware is offline I fold for Overclock.net Overclocked Account lattyware's Gallery   Reply With Quote
Old 08-26-08   #7 (permalink)
PC Gamer
 
-Darkness-'s Avatar
 
Join Date: Apr 2008
Location: Far, far away.
Posts: 63

Rep: 4 -Darkness- Unknown
Unique Rep: 3
Trader Rating: 0
Default

kthxbai :P
__________________
Quote:
Originally Posted by Base64
SWYgeW91IGNhbiByZWFkIHRoaXMsIHlvdSBhcmUgb3Zlci1lZH VjYXRlZC4=

Code:
If bored = true then
webbrowser1.browse ("www.overclock.net")
      End If
-Darkness- is offline   Reply With Quote
Old 08-26-08   #8 (permalink)
Programmer
 
amd nvidia

Join Date: Mar 2008
Location: UIUC
Posts: 236

Rep: 34 OasisGames is acknowledged by some
Unique Rep: 30
Trader Rating: 0
Default

Last I checked, VB (under Mono) can't open and use a Glade file. But maybe my understanding of GTK# is lacking.
__________________
Retired Compiz Developer
Ubuntu Alpha Tester

System: Harmony
CPU
Phenom II X4 (4x 3.0GHz)
Motherboard
BIOSTAR TA790GXB
Memory
4GB DDR2
Graphics Card
ECS GeForce 9800 GT
Hard Drive
1TB Seagate 7200RPM
Sound Card
Built-in ATI 3870 HD + old SoundBlaster Audigy SE
Power Supply
mushkin 550200 550W
Case
COOLER MASTER Elite 330
OS
Ubuntu Linux 9.10 (x86 ...)
Monitor
2x ViewSonic VA2226W (22" LCDs)

Last edited by OasisGames : 08-26-08 at 07:08 PM
OasisGames is online now   Reply With Quote
Old 08-26-08   #9 (permalink)
New to Overclock.net
 
DarkNite's Avatar
 
intel ati

Join Date: Dec 2007
Location: Montreal
Posts: 3,104

Rep: 195 DarkNite is acknowledged by manyDarkNite is acknowledged by many
Unique Rep: 153
Trader Rating: 2
Default

integer not interger
__________________
Lorna DEREK. Rich-a-la-la - Sarahhh. VI-KY.

System: Ventolin
CPU
e4600 @ 3.5
Motherboard
GA EP45-DS3R
Memory
4GB Mushkin
Graphics Card
Sapphire HD4850
Hard Drive
300Gb WD
Sound Card
Xonar DX
Case
A900
CPU cooling
Vendetta II
GPU cooling
VF1000
OS
W7 RC
Monitor
SyncMaster 216BW 55.88cm
DarkNite is offline   Reply With Quote
Old 08-26-08   #10 (permalink)
Intel Overclocker
 
intel nvidia

Join Date: Apr 2006
Location: London
Posts: 766

Rep: 55 BugBash is acknowledged by some
Unique Rep: 52
Trader Rating: 0
Default

Thanks for that!

I learnt 68000 assembly back in the early 90`s not long out of school were ya learnt BASIC in `Computer Studies` on crusty old BBC micros! (they had econet which was cool!)

what seems to go for `Computer Studies` these days??? (in the UK BTW!!)

MS Office, Internet explorer and Fakebook.....

Why do they not teach something that could get them interested in programing and become the next generation of arse kicking game creators???
__________________

The Black Mesa Survivors Club

2nd Rig:
HP Pavilion Q6600, 4GB, 2x500GB, Nvidia 9600GS 768MB @Stock for now!

System: My System
CPU
P4 3.06HT@ 3.49 s478
Motherboard
Abit IC7-G
Memory
2.5GB DDR400
Graphics Card
XFX 7800GS 256MB AGP
Hard Drive
WD5000YS(500GB)+320GB+40GB
Sound Card
SB Audigy 4
Power Supply
Tagan 480-U22
Case
Silverstone TJ-05 Black
CPU cooling
Thermalrite XP-120
GPU cooling
Stock
OS
Windows XP SP3
Monitor
HP L2208w Optoma DX606
BugBash is offline   Reply With Quote
Reply

Tags
glade, gui, programming, python, tutorial


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -5. The time now is 08:48 AM.


Overclock.net is a Carbon Neutral Site Creative Commons License

Terms of Service / Forum Rules | Privacy Policy | DMCA Info | Advertising | Become an Official Vendor
Copyright © 2009 Shogun Interactive Development. Most rights reserved.
Page generated in 0.17919 seconds with 9 queries