标签:des style blog http color io 使用 ar strong
This is a note for https://class.coursera.org/interactivepython-005
In week two, I have learned:
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 module
import simplegui
# Event handler
def tick():
print "tick!"
# Register handler
timer = simplegui.create_timer(1000, tick)
# Start timer
timer.start()
when you want to change the global variables, use global, ifelse you don‘t need global.(不需更改全局变量,只是想使用全局变量的值的时候,不需要声明global)
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 module import simplegui # Define global variables (program state) counter = 0 # Define "helper" functions def increment(): global counter counter = counter + 1 # Define event handler functions def tick(): increment() print counter def buttonpress(): global counter counter = 0 # Create a frame frame = simplegui.create_frame("SimpleGUI Test", 100, 100) frame.add_button("Click me!", buttonpress) # Register event handlers timer = simplegui.create_timer(1000, tick) # Start frame and timers frame.start() timer.start()
Simple Calculator
Data
Store
Operand
Operations
Swap
Add
Subtract
Multiple
Divide
Computation
Store = store operation operand
# calculator with all buttons import simplegui # intialize globals store = 0 operand = 0 # event handlers for calculator with a store and operand def output(): """prints contents of store and operand""" print "Store = ", store print "Operand = ", operand print "" def swap(): """ swap contents of store and operand""" global store, operand store, operand = operand, store output() def add(): """ add operand to store""" global store store = store + operand output() def sub(): """ subtract operand from store""" global store store = store - operand output() def mult(): """ multiply store by operand""" global store store = store * operand output() def div(): """ divide store by operand""" global store store = store / operand output() def enter(t): """ enter a new operand""" global operand operand = int(t) output() # create frame f = simplegui.create_frame("Calculator",300,300) # register event handlers and create control elements f.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 rolling f.start()
【python】An Introduction to Interactive Programming in Python(week two)
标签:des style blog http color io 使用 ar strong
原文地址:http://www.cnblogs.com/dplearning/p/4002689.html