Skip to content

Instantly share code, notes, and snippets.

@shifei010
Created October 7, 2012 03:56
Show Gist options
  • Save shifei010/3847044 to your computer and use it in GitHub Desktop.
Save shifei010/3847044 to your computer and use it in GitHub Desktop.
HOWTO Create Python GUIs using HTML
http://www.aclevername.com/articles/python-webgui/
ipc.js
function send(msg) {
document.title = "null";
document.title = msg;
}
demo.xhtml
<script src="ipc.js" type="text/javascript"></script>
<script type="text/javascript">
function got_a_click() {
// NOTE: send is a JavaScript function that is defined in "ipc.js".
// This send function is how messages are sent from HTML
// to Python:
send('"got-a-click"');
}
function document_ready() {
send('"document-ready"');
document.getElementById('messages').addEventListener('click', got_a_click, false);
}
document.addEventListener('DOMContentLoaded', document_ready, false);
</script>
<p class="uptime">
Python uptime:
<span id="uptime-value">?</span> seconds.
</p>
<p id="messages">
Click here (yes, anywhere here)...<br/>
</p>
webgui.py
def launch_browser(uri, quit_function=None, echo=True):
...
message_queue = Queue.Queue()
def title_changed(title):
if title != 'null': message_queue.put(title)
def web_recv():
if message_queue.empty():
return None
else:
msg = message_queue.get()
if echo: print '>>>', msg
return msg
def web_send(msg):
if echo: print '<<<', msg
asynchronous_gtk_message(implementation.inject_javascript)(browser, msg)
return browser, web_recv, web_send
demo.py
from simplejson import dumps as to_json
from simplejson import loads as from_json
class Global(object):
quit = False
@classmethod
def set_quit(cls, *args, **kwargs):
cls.quit = True
def main():
...
last_second = time.time()
uptime_seconds = 1
clicks = 0
while not Global.quit:
current_time = time.time()
again = False
msg = web_recv()
if msg:
msg = from_json(msg)
again = True
if msg == "got-a-click":
clicks += 1
web_send('document.getElementById("messages").innerHTML = %s' % to_json('%d clicks so far' % clicks))
# If you are using jQuery, you can do this instead:
# web_send('$("#messages").text(%s)' % to_json('%d clicks so far' % clicks))
if current_time - last_second >= 1.0:
web_send('document.getElementById("uptime-value").innerHTML = %s' % to_json('%d' % uptime_seconds))
# If you are using jQuery, you can do this instead:
# web_send('$("#uptime-value").text(%s)' % to_json('%d' % uptime_seconds))
uptime_seconds += 1
last_second += 1.0
if again: pass
else: time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment