I'm no UI or web designer, though I have made a bunch of simple Tkinter-based GUIs that are simple wrappers to test lower-level code and hardware, such as protocol and data acquisition testers for equipment connected over a serial port or network. Using Python and Tkinter permits my apps to run on every platform supporting Python.
Now I need to migrate my GUIs to support single-user remote access, while still supporting access by local users. And I'd still like the program to be portable across platforms, and even have it be possible to be made into a binary executable (via py2exe, pyinstaller, py2app, etc.)
Are there any toolkits that support Tkinter-like simplicity? Ideally, I'd like to do a line-for-line rewrite to swap Tkinter for something else, rather than reimplement or extensively refactor my apps.
I have found Web2Py and pyjs/Pyjamas, but they seem to be overkill for my simple needs. I also searched for a solution based on a single-instance (or single window) VNC or NX or RDP host, but found nothing applicable.
What is the most direct way to "remote-ify" my Tkinter GUIs?
If I do need to completely dump my Tkinter architecture/code and start over from scratch, what approach would best meet my needs?
I would recommend checking out CherryPy. It's really easy to wrap your head around and get a quick server up and running - it doesn't have the overhead/complexity that a lot of other frameworks impose (Django!!). Unfortunately you will have to rewrite the UI in html, but ultimately it will most likely be worth the effort. Check out Twitter's Bootstrap to get the ball rolling on a quick and attractive UI that just "works".
An example of how concise a CherryPy app can be:
import cherrypy
class SessionExample:
#cherrypy.expose
def index ( self ):
if cherrypy.session.has_key ( 'color' ):
out = "<font color='{0}'>{0}</font>".format(cherrypy.session['color'])
else:
out = ""
return out + ("<form method='POST' action='setColor'>\n"
"Please choose a color:<br />\n"
"<select name='color'>\n"
"<option>Black</option>\n"
"<option>Red</option>\n"
"<option>Green</option>\n"
"<option>Blue</option>\n"
"</select><br />\n"
"<input type='submit' value='Select' />\n"
"</form>"
#cherrypy.expose
def setColor (self, color):
cherrypy.session ['color'] = color
return "Color set to {}".format(color)
cherrypy.config.update({
"server.socketPort" = 8080,
"server.environment" = "development",
"server.threadPool" = 10,
"sessionFilter.on" = True
})
cherrypy.root = SessionExample()
cherrypy.server.start()
Navigate to localhost:8080 in a web browser and you should see a color picker. Simple!
Related
I have an Interactive Brokers [IB] account and am using the IB API to make an automated trading system in python. Version 1.0 is nearing the test stage.
I am thinking about creating a GUI for it so that I can real-time watch various custom indicators and adjust trading parameters. It is all (IB TWS/IB Gateway and my app) running on my local windows 10 pc (I could run it on Ubuntu if that made it easier) with startup config files presently being the only way to adjust parameter and then watch the results scroll by on the console window.
Eventually I would like to run both IB TWS/IB Gateway and the app on Amazon EC2/AWS and access it from anywhere. I only mention this as may be a consideration on how to setup the GUI now to avoid having to redo it then.
I am not going to write this myself and will contract someone else to do it. After spending 30+ hrs researching this I still really have no idea on what the best way would be to implement this (browser based, standalone app, etc.) and/or what skills the programmer would need for me to describe the job.
An estimate on how long it would take to get a bare bones GUI real-time displaying data from my app and real-time sending inputs back to my app would be additionally helpful.
The simplest and quickest way will probably be to add GUI directly to your Python App. If you don't need it to be pretty or to run on mobile, I'd say go with TKinter for simplicity. Then, connect to wherever the App is located and control it remotely.
Adding another component that will communicate with your Python App introduces a higher level of complexity which I think is redundant in this case.
You didn't specify in details what kind of data you will require the app to display. If this includes any form of charting, I'd use an existing charting software such as Ninjatrader / Multicharts / Sierracharts to run my indicators and see the positions status, and restrict the GUI of the python app to adjusting the trading parameters and reporting numerical stats.
I want to make a application that run as a web application or desktop application, I know how to implement for a web server using Django or Flask, i prefer Django, but is there any way to port it to a desktop application too?
I found a nodewebkit that maybe give me the solution but, I don`t have any idea on how to use it.
import wx
from wx.lib.iewin import IEHtmlWindow
a = wx.App(redirect=False)
f = wx.Frame(None,-1,"My Desktop Application")
browser = IEHtmlWindow(f)
browser.Navigate("http://google.com")
f.Show()
a.MainLoop()
is a pretty good way for a remote web page to pretend to be a windows application ... assuming thats what you are asking for.. (this uses wxPython so of coarse you will need to install it)
Me personally prefer node-webkit(renamed to nwjs) for this kind of things. Its very easy and powerful, you should give it a try. here are some tutorials.
this,
this and
this. here is the github page nwjs.
but if your background is in python not nodejs then take a look at cefpython
I've created a simple gstreamer-based python audio application with a GTK+ GUI for picking and playing a webstream from a XML list. Then I connected my PC speakers output to the input of an old stereo receiver with large loudspeakers and presto, I have a pretty good sound system that is heard over most of my home.
Now I'd like to add a web user-interface to remote control the application from a room other than the one with the computer but so far all my attempts have been fruitless.
In particular I wonder if it is possible to create a sort of socket with signals like those of GTK GUIs to run methods that change gstreamer parameters.
Or is there a more realistic/feasible strategy?
Thanks in advance for any help!
You could use Bottle, a very simple micro web-framework.
Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.
Hello world:
from bottle import route, run
#route('/hello/:name')
def index(name='World'):
return '<b>Hello %s!</b>' % name
run(host='localhost', port=8080)
The fastest and easiest way would probably be using cgi-scripts. If you want a more sophisticated approach you could consider using a webframework like django, turbogears or the likes.
I would suggest using one of the lighter-weight pure-Python web server options and either write a stand-alone WSGI application or use a micro-framework.
Gevent would be a good option: http://www.gevent.org/servers.html
Here is a sample implementation of a WSGI application using Gevent:
https://bitbucket.org/denis/gevent/src/tip/examples/wsgiserver.py#cl-4
For a micro-framework, I'd suggest using Flask.
How to convert the web site develpoed in django, python into desktop application.
I am new to python and django can you please help me out
Thanks in Advance
I think you should just create an application that connects to the webserver. There is a good answer to getting RESTful API calls into your django application. This means you'd basically just be creating a new front-end for your server.
Using django-rest-interface
It doesn't make sense to rewrite the entire django application as a desktop application. I mean, where do you want to store the data?
For starters, you'll have to replace the web UI with a desktop technology like Tk/Tcl.
If you do that, you may not want to use HTTP as the protocol between the client and the services.
Django is a web framework. If you're switching to a desktop, you'll have to forego Django.
I would try to replicate the Django application functionality with the PyQt toolkit.
You can in fact embed web content in PyQt applications, with the help of QtWebKit. I would post some potentially useful links, but apparently I have too low a reputation to post more than one :)
There are two places you can go to try to decouple the view and put it into a new desktop app. First you can use the existing controller and model and adapt a new view to that. Second, you can use only the existing model and build a new view and controller.
If you haven't adhered closely enough to the MVC principles that you can detach the model from the rest of the application, you can simply rewrite the entire thing. if you are forced to go this route, bail on django and http entirely (as duffymo suggests above).
You have to also evaluate these solutions based upon performance requirements and "heaviness" of the services. If you have stringent performance requirements then relying on the HTTP layer just gets in the way, and providing a simple API into your model is the way to go.
There are clearly a lot of possibly solutions but this is the approach I would take to deciding what the appropriate one is...
It is possible to convert a django application to a desktop app with pywebview with some line of codes. Frist create a python file gui.py in directory where manage.py exists. install pywebview through pip, the write the code in gui.py
import os
import sys
import time
from threading import Thread
import webview
def start_webview():
window = webview.create_window('Hello world', 'http://localhost:8000/', confirm_close=True, width=900, height=600)
webview.start()
window.closed = os._exit(0)
def start_startdjango():
if sys.platform in ['win32', 'win64']:
os.system("python manage.py runserver {}:{}".format('127.0.0.1', '8000'))
# time.sleep(10)
else:
os.system("python3 manage.py runserver {}:{}".format('127.0.0.1', '8000'))
# time.sleep(10)
if __name__ == '__main__':
Thread(target=start_startdjango).start()
start_webview()
then run gui.py with the command python gui.py. IT will create a window like desktop app
There's a project called Camelot which seems to try to combine Django-like features on the desktop using PyQt. Haven't tried it though.
I am thinking about a similar Problem.
Would it be enough to habe a minimal PyQt Gui that enables you to present the djando-website from localhost (get rid of TCP/HTTPS on loop interface somehow) via QtWebkit?
All you seem to need is to have a minimal Python-Broser, that surfs the build in Webserver (and i guess you could even call Django directly for the html-payload without going over the HTTP/TCP layers).
I have django manage.py runserver in .bat file and a localhost bookmark bar in a browser and whola a django-desktop-app. Or make your own browser that opens localhost. Creating a web-browser with Python and PyQT
I want to create a very simple python web app. I don't need Django or any other web framwwork like that. Isn't there a simpler way to create a web app in python?
Thanks
If you don't need Django, try web.py
http://webpy.org/
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
Sure! For example,
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
this is a web app -- if you save it into a file in an appropriate directory of a machine running a web server and set the server's configuration properly (depending on the server); the article I pointed to specifically shows how to deploy this web app to Google App Engine, but just about any web server can serve CGI apps, and this is a simple example thereof.
Of course, CGI has its limits, and you can use more sophisticated approaches (still short of a framework!) such as WSGI (also universally supported, if nothing else because it can run on top of CGI -- but in most cases you can also deploy it in more advanced ways) and possibly some of the many excellent utility components you can deploy with WSGI to save you work in coding certain parts of your apps.
WSGI is probably what you are looking for. Though there are several lightweight python web frameworks around which are less monolithic than django.
The truth is that you do need a framework of some sort even if it's extremely minimal. You can use WSGI as a base and at least you're doing a little better. Python is a very powerful, very unspecific programming language so if you decide to do it without a framework you're going to have to rewrite huge amounts of code that you may be taking for granted.
If you do decide to go with something other than Django try this list and maybe you'll find something simple enough that you'll feel good about it. :)
first we have to install the package.
In terminal:
>>> pip install PySimpleGUI
Then go on type in this code...
# Code
import PySimpleGUI as sg
sg.theme('add_your_bgcoloor_here') layout = [[sg.Text('This is for the text')],
[sg.InputText('This is to input the texts')],
[sg.InputCombo(['Option 1', 'Option 2', 'Option 3'])
[sg.Radio('Checkbox', 1)],
[sg.Spin([x for x in range(1, 100)], initial_value=1)],
[sg.Button('go']]
# creating our window window = sg.Window('Window, layout)
# defining the events and the value in the layout using while True statement while True:
event, values = window.read()
# defining our button 'go' (sg.Button('go'))
if event == 'go':
break window.close()
Yep WSGI...
def hello_wsgi(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
If you want to abstract this in terms of request/response to get a little further away from http try webob.
from webob import Request, Response
def hello_wsgi(environ, start_response):
request = Request(environ)
#do something with the request
#return a response
return Response("Hello World!")(environ, start_response)
I use bottle all the time as a minimal web framework.
It is very simple to use.
as a minimum example - taken from the web site :
from bottle import route, run
#route('/hello/:name')
def index(name='World'):
return '<b>Hello %s!</b>' % name
run(host='localhost', port=8080)
you simply associate url (route) to functions. This one even get an optional argument.
It has an optional light templating language, and you can tweak it a lot for our needs. Very powerful.
It is also very easy to instal - as it comes as a single file, standing along your app, and is pure compliant python. It is also very easy to debug, with a nice autoreload on modif while in development mode.
As a final advantages, it runs smoothly under pypy - thus providing a speed boost over other frameworks.
Now a days it is better to use PhusionPassenger Standalone or with NGINX using same technique as PHP by proxy passing it to FastCGI in case of PHP and WSGI for Python.
The URL and all explanation for Passenger can be found: Here
All information about Python running on NGINX over FastCGI, uWSGI or Passenger
About frameworks that wrap Python for easier Web development I do recommend Django if it is a larger application and once you get the hang of it Django isn't that hard actually.
Good Luck!
You can try Appier (https://github.com/hivesolutions/appier). Here's a sample app:
import appier
class HelloApp(appier.App):
#appier.route("/", "GET")
def hello(self):
return "Hello World"
HelloApp().serve()
And here's how you run it:
pip install appier
python hello.py
Disclaimer: This framework is part of the open-source portfolio of my company. We built the framework to make the code for our consulting work as simple and clean as possible (to improve our efficiency). The project is very active, as we use the framework all the time, however, the caveat is that we've only started talking about it publicly recently, so there's no community around it yet. However, for that very reason, we're very open to cooperating closely with early bird developers in improving our documentation and adding new features.