首页 > 代码库 > 【python】An Introduction to Interactive Programming in Python(week two)
【python】An Introduction to Interactive Programming in Python(week two)
This is a note for https://class.coursera.org/interactivepython-005
In week two, 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 "tick!"# Register handlertimer = simplegui.create_timer(1000, tick)# Start timertimer.start()
2. global variables
when you want to change the global variables, use global, ifelse you don‘t need global.(不需更改全局变量,只是想使用全局变量的值的时候,不需要声明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 moduleimport simplegui# Define global variables (program state)counter = 0# Define "helper" functionsdef increment(): global counter counter = counter + 1 # Define event handler functionsdef tick(): increment() print counterdef buttonpress(): global counter 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
Swap
Add
Subtract
Multiple
Divide
Computation
Store = store operation operand
# calculator with all buttonsimport simplegui# intialize globalsstore = 0operand = 0# event handlers for calculator with a store and operanddef 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 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 two)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。