from browser import document, htmlcalc = html.TABLE()calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) + html.TH("C", id="clear"))lines = ["789/", "456*", "123-", "0.=+"]calc <= (html.TR(html.TD(x) for x in line) for line in lines)document <= calc
calc <= (html.TR(html.TD(x) for x in line) for line in lines)
可以看出,所有的按鈕都被建立為td标簽,是以我們要獲得所有這些按鈕是否被點選,僅需要:
for button in document.select("td"): button.bind("click", action)
意思是,按鈕被點選後便執行 action 操作,action操作定義如下:
def action(event): """Handles the "click" event on a button of the calculator.""" # The element the user clicked on is the attribute "target" of the # event object element = event.target # The text printed on the button is the element's "text" attribute value = element.text if value not in "=C": # update the result zone if result.text in ["0", "error"]: result.text = value else: result.text = result.text + value elif value == "C": # reset result.text = "0" elif value == "=": # execute the formula in result zone try: result.text = eval(result.text) except: result.text = "error"