This was a note for https://class.coursera.org/interactivepython-005
In Week II, I have learned:
1.event-drvien Programing
4 Event Types:
Input: Button, textbox
Keyborad: Key up, key down
Mouse: Click, drag
Timer
Example
# Example of a simple event-driven program# codeskulptor GUI moduleimport simplegui# event Handlerdef tick (): print "t ick! " # Register Handlertimer = Simplegui.create_timer (+, tick) # Start Timertimer.start ()
2. Global variables
When you want-to-change the global variables, use global, ifelse-t need global. (No global variables need to be changed, only when you want to use the values of global variables, you don't have to declare global)
3. Simplegui
Program structure with 7 steps:
①globals (state)
②helper functions
③classes
④define Event handlers
⑤create A Frame
⑥register Event handlers
⑦start Frame & Timers
#Simplegui Program Template#Import the moduleImportSimplegui#Define Global Variables ( program state)Counter =0#Define "helper" functionsdefincrement ():GlobalCounter Counter= counter + 1#Define event handler functionsdeftick (): Increment ()PrintcounterdefButtonPress ():GlobalCounter Counter=0#Create A Frameframe = Simplegui.create_frame ("Simplegui Test", 100, 100) Frame.add_button ("Click me!", ButtonPress)#Register Event HandlersTimer = Simplegui.create_timer (1000, tick)#Start frame and timersFrame.start () Timer.start ( )
Simple Calculator
Data
Store
Operand
Operations
Print
Swap
Add
Subtract
Multiple
Divide
Computation
store = store operation operand
#Calculator with all buttonsImportSimplegui#intialize Globalsstore =0operand=0#event handlers for calculator with a store and operanddefoutput ():"""prints contents of store and operand""" Print "Store =", StorePrint "Operand =", operandPrint "" defswap ():"""swap contents of store and operand""" Globalstore, operand store, operand=operand, store output ()defAdd ():"""add operand to store""" GlobalStore Store= store +operand output ()defSub ():"""subtract operand from store""" GlobalStore Store= Store-operand output ()defmult ():"""multiply store by operand""" GlobalStore Store= Store *operand output ()defDiv ():"""divide store by operand""" GlobalStore Store= store/operand output ()defEnter (t):"""Enter a new operand""" Globaloperand operand=int (t) output ()#Create framef = simplegui.create_frame ("Calculator", 300,300)#register event handlers and create control elementsF.add_button ("Print", Output, 100) F.add_button ("Swap", swap, 100) F.add_button ("ADD", add, 100) F.add_button ("Sub", Sub, 100) F.add_button ("Mult", Mult, 100) F.add_button ("Div", Div, 100) F.add_input ("Enter", enter, 100)#Get frame rollingF.start ()
"Python" an Introduction to Interactive programming in Python (week)