Python Web/Brython

[Python web] 3. 특성 (이벤트) 적용해보기(Brython)

1.계산기 만들기

간단한 계산기를 만드는 예제이다

 

2. 실행

1. 간단한 실행 방법 

 

 

3. 파일구조

<folder>

Folder─┬─ index.htm
             ├─ style.css
             └─ script ─┬─ brython.js
                                 ├─ brython.min.js
                                 ├─ brython_stdlib.min.js
                                 └─ python.py

<index.html>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <!-- brython 가져오기  오프라인 -->
        <script type="text/javascript" src="script/brython.min.js"></script>
        <script type="text/javascript" src="script/brython_stdlib.min.js"></script>

    <!-- css 가져오기 -->
    <link rel="stylesheet" type="text/css" href="css/style.css" />
       
    <!-- python 파일 사용하기 -->
    <script type="text/python" src="script/python.py"></script>
   
    </head>
    <body onload="brython()">
    </body>
</html>

<css/style.css>

*{
	font-family: sans-serif;
	font-weight: normal;
	font-size: 1.1em;
}
td{
	background-color: white;
	padding: 10px 30px 10px 30px;
	border-radius: 0.2em;
	text-align: center;
	cursor: default;
}
#result{
	width:200px;
	border-color: #000;
	border-width: 5px;
	border-style: solid;
	padding: 10px 30px 10px 30px;
	text-align: right;
	background-color: black;
	color: white;
	border-radius: 0.2em;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}
body {
	position:relative;
	
}
table {
	display:inline-block;
	left: auto;
	table-layout:fixed;
	word-break: break-all;
	width: 100px;
}

<script/python.py>

from browser import document, html

calc = html.TABLE()
calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) + html.TD("C"))
lines = ["789/", "456*", "123-", "0.=+"]

calc <= (html.TR(html.TD(x) for x in line) for line in lines)

document <= calc

result = document["result"] 

def action(event):
    element = event.target
    value = element.text
    if value not in "=C":
        if result.text in ["0", "error"]:
            result.text = value
        else:
            result.text = result.text + value
    elif value == "C":
        result.text = "0"
    elif value == "=":
        try:
            result.text = eval(result.text)
        except:
            result.text = "error"

for button in document.select("td"):
    button.bind("click", action)

4.  끝

입력시 바뀌는 계산기다 이벤트를 자유롭게 사용가능 할거 같다 이것으로 튜토리얼은 끝마치 겟다