article

Friday, June 24, 2016

Wordpress - You do not have sufficient permissions to access this page.

Wordpress - You do not have sufficient permissions to access this page.

You should check your wp-config.php file and if you find this line
define('DISALLOW_FILE_MODS',true);
change its value to false:
define('DISALLOW_FILE_MODS',false);
 

Sunday, June 12, 2016

Python Django - Creating Simple Views

Python Django - Creating Simple Views

In Django, views have to be created in the app views.py file.

See the following view −


 
from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

A template: myapp/templates/hello.html
myapp\templates\hello.html

add url C:\myprojectdjango\myprojectdjango\urls.py

 
from django.conf.urls import patterns, include, url
from django.contrib import admin

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),)

Run
python manage.py runserver 
http://127.0.0.1:8000/hello/

Saturday, June 11, 2016

Python Django - Apps Life Cycle

Python Django - Apps Life Cycle

Every application has an objective and can be reused into another project, like the contact form on a website can be an application, and can be reused for others.

Create an Application

We assume you are in your project folder. In our main “myprojectdjango” folder, the same folder than manage.py −

C:\myprojectdjango>python manage.py startapp myapp

You just created myapp application and like project, Django create a “myapp” folder with the application structure −

myapp/
   __init__.py
   admin.py
   models.py
   tests.py
   views.py

__init__.py − Just to make sure python handles this folder as a package.
admin.py − This file helps you make the app modifiable in the admin interface.
models.py − This is where all the application models are stored.
tests.py − This is where your unit tests are.
views.py − This is where your application views are.

Get the Project to Know About Your Application

we have our "myapp" application, now we need to register it with our Django project "myprojectdjango". To do so, update INSTALLED_APPS tuple in the settings.py file of your project (add your app name) −

myprojectdjango\myprojectdjango\settings.py

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp', #created application myapp folder
)

Python Flask - Sending Form Data to Template and Cookies

Python Flask - Sending Form Data to Template and Cookies
 
Flask – Sending Form Data to Template

In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to table.html.
 
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('student.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/
#if click submet call result http://127.0.0.1:5000/result   
Given below is the HTML script of student.html.

   
      
Name
Physics
Chemistry
Maths

Code of template (result.html) is given below −

   
      
         {% for key, value in result.iteritems() %}

{% endfor %}
      
{{ key }} {{ value }}
Flask – Cookies
A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie.
from flask import Flask, render_template, request,make_response
app = Flask(__name__)

@app.route('/') # http://localhost:5000/
def index():
   return render_template('index.html')
 
@app.route('/setcookie', methods = ['POST', 'GET']) # http://localhost:5000/setcookie
def setcookie():
   if request.method == 'POST':
      user = request.form['nm']
    
   resp = make_response(render_template('readcookie.html'))
   resp.set_cookie('userID', user)
    
   return resp
 
@app.route('/getcookie') # http://localhost:5000/getcookie
def getcookie():
   name = request.cookies.get('userID')
   return '

welcome '+name+'

' if __name__ == '__main__': app.run(debug = True)
index.html

   
      

Enter userID




Python Flask HTTP Method, Templates, Static Files

Python Flask

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.

The following table summarizes different http methods −

GET
Sends data in unencrypted form to the server. Most common method.   
HEAD
Same as GET, but without response body   
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.   
PUT
Replaces all current representations of the target resource with the uploaded content.   
DELETE
Removes all current representations of the target resource given by a URL

demonstrate the use of POST method in URL routing


   
      
      
Enter Name:
Now enter the following script in Python shell.
 
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)
Flask – Templates
Jinja2 template. HTML file can be engine rendered by the render_template() function
 
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('hello.html')

if __name__ == '__main__':
   app.run(debug = True)
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
Application folder
  • Hello.py
  • templates
    • hello.html
The following code is saved as hello.html in the templates folder.

   
      

Hello {{ name }}!

Next, run the following script from Python shell.
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost:5000/hello/tutorial101
The variable part of URL is inserted at {{ name }} place holder.

The Jinga2 template engine uses the following delimiters for escaping from HTML.

{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements

following example, use of conditional statement in the template is demonstrated.

 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost/hello/60
HTML template script of hello.html is as follows −

   
   
      {% if marks>50 %}
      

Your result is pass!

{% else %}

Your result is fail

{% endif %} Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}
Flask – Static Files
A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. these files are served from static folder in your package or next to your module and it will be available at /static on the application. In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)
   
   
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)
The HTML script of index.html is given below.

   
      
   
   
      
   

Hello.js contains sayHello() function.
 function sayHello() {
   alert("Hello World")
}

Python Flask Routing, Variable rules, URL Building

Python Flask - Routing, Variable rules, URL Building

Flask – Routing

The route() decorator in Flask is used to bind URL to a function. For example −


 
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
   return 'hello world'

if __name__ == '__main__':
   app.run()
   
#http://127.0.0.1:5000/hello
Flask – Variable Rules It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as . It is passed as a keyword argument to the function with which the rule is associated.
 
from flask import Flask
app = Flask(__name__)

@app.route('/hello/')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/hello/tutorial101
The following output will be displayed in the browser.
Hello tutorial101!
In the following code, all these constructors are used.
 
from flask import Flask
app = Flask(__name__)

@app.route('/blog/')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()
#http://127.0.0.1:5000/blog/11
#http://localhost:5000/rev/1.1
The given number is used as argument to the show_blog() function. The browser displays the following output −
Blog Number 11
Revision Number 1.100000
Flask – URL Building
The url_for() function is very useful for dynamically building a URL for a specific function.
The following script demonstrates use of url_for() function.
 
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/admin
#http://127.0.0.1:5000/guest/ednalan
#http://127.0.0.1:5000/guest/ednalan   
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.
The application response in browser is −
Hello Admin
Hello mvl as Guest

Python Flask install and run

 Python Flask Install and run

Flask is a web application framework written in Python. Armin Ronacher, who leads an international group of Python enthusiasts named Pocco, develops it. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.

1. Create folder name flaskmyproject
2. py -3 -m venv venv
3. venv\Scripts\activate
4. pip install flask
5. flask --version
6. mkdir demoapp
7. flask run

http://127.0.0.1:5000/

app.py
 
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello Worlddfdsf'

if __name__ == '__main__':
   app.run()

RUN
C:\>cd flaskmyproject
C:\flaskmyproject>venv\Scripts\activate
(venv) C:\flaskmyproject>cd demoapp
(venv) C:\flaskmyproject\demoapp>flask run
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Python How to check if a network port is open

Python How to check if a network port is open
 
import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

Friday, June 10, 2016

Python read csv

Python read csv
 
import csv

csvfilename = "server_L2.csv"

print "Printing all rows"
with open(csvfilename, 'rb') as csvfile:
 reader = csv.reader(csvfile, delimiter='\t')
 for row in reader:
  print "   ", row
print ""

print "Printing all rows using header line"
with open(csvfilename) as csvfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    for row in reader:
        print "   ", row
print ""

wxpython widgets wx.ListCtrl

wxpython widgets wx.ListCtrl

A wx.ListCtrl is a graphical representation of a list of items

wx.ListCtrl styles

wx.LC_LIST
wx.LC_REPORT
wx.LC_VIRTUAL
wx.LC_ICON
wx.LC_SMALL_ICON
wx.LC_ALIGN_LEFT
wx.LC_EDIT_LABELS
wx.LC_NO_HEADER
wx.LC_SORT_ASCENDING
wx.LC_SORT_DESCENDING
wx.LC_HRULES
wx.LC_VRULES
 
import wx
import sys

packages = [('jessica alba', 'pomona', '1981'), ('sigourney weaver', 'new york', '1949'),
    ('angelina jolie', 'los angeles', '1975'), ('natalie portman', 'jerusalem', '1981'),
    ('rachel weiss', 'london', '1971'), ('scarlett johansson', 'new york', '1984' )]



class Actresses(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(380, 230))

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        panel = wx.Panel(self, -1)

        self.list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT) #We create a wx.ListCtrl with a wx.LC_REPORT style
        self.list.InsertColumn(0, 'name', width=140)
        self.list.InsertColumn(1, 'place', width=130)
        self.list.InsertColumn(2, 'year', wx.LIST_FORMAT_RIGHT, 90)

        for i in packages:
            index = self.list.InsertStringItem(sys.maxint, i[0])
            self.list.SetStringItem(index, 1, i[1])
            self.list.SetStringItem(index, 2, i[2])

        hbox.Add(self.list, 1, wx.EXPAND)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

app = wx.App()
Actresses(None, -1, 'actresses')
app.MainLoop()

wxpython widgets wx.html Help window

wxpython widgets wx.html Help window

 wx.html.HtmlWindow to provide help in our application. We can create a standalone window or we can create a window that is going to be a part of the application. The following script will create a help window using the latter idea.
 
import wx
import wx.html as html

class HelpWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(570, 400))

        toolbar = self.CreateToolBar()
        toolbar.AddLabelTool(1, 'Exit', wx.Bitmap('img/quit.png'))
        toolbar.AddLabelTool(2, 'Help', wx.Bitmap('img/help.png'))
        toolbar.Realize()

        self.splitter = wx.SplitterWindow(self, -1)
        self.panelLeft = wx.Panel(self.splitter, -1, style=wx.BORDER_SUNKEN)

        self.panelRight = wx.Panel(self.splitter, -1)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        header = wx.Panel(self.panelRight, -1, size=(-1, 20))
        header.SetBackgroundColour('#6f6a59')
        header.SetForegroundColour('WHITE')
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        st = wx.StaticText(header, -1, 'Help', (5, 5))
        font = st.GetFont()
        font.SetPointSize(9)
        st.SetFont(font)
        hbox.Add(st, 1, wx.TOP | wx.BOTTOM | wx.LEFT, 5)

        close = wx.BitmapButton(header, -1, wx.Bitmap('img/quit.png', wx.BITMAP_TYPE_PNG), 
  style=wx.NO_BORDER)
        close.SetBackgroundColour('#6f6a59')
        hbox.Add(close, 0)
        header.SetSizer(hbox)

        vbox2.Add(header, 0, wx.EXPAND)

        help = html.HtmlWindow(self.panelRight, -1, style=wx.NO_BORDER)
        help.LoadPage('help.html')
        vbox2.Add(help, 1, wx.EXPAND)
        self.panelRight.SetSizer(vbox2)
        self.panelLeft.SetFocus()

        self.splitter.SplitVertically(self.panelLeft, self.panelRight)
        self.splitter.Unsplit()

        self.Bind(wx.EVT_BUTTON, self.CloseHelp, id=close.GetId())
        self.Bind(wx.EVT_TOOL, self.OnClose, id=1)
        self.Bind(wx.EVT_TOOL, self.OnHelp, id=2)

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)

        self.CreateStatusBar()

        self.Centre()
        self.Show(True)

    def OnClose(self, event):
        self.Close()

    def OnHelp(self, event):
        self.splitter.SplitVertically(self.panelLeft, self.panelRight)
        self.panelLeft.SetFocus()

    def CloseHelp(self, event):
        self.splitter.Unsplit()
        self.panelLeft.SetFocus()

    def OnKeyPressed(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_F1:
            self.splitter.SplitVertically(self.panelLeft, self.panelRight)
            self.panelLeft.SetFocus()


app = wx.App()
HelpWindow(None, -1, 'HelpWindow')
app.MainLoop()
help.html



Table of Contents

Basic Statistics
Overview of elementary concepts in statistics. Variables. Correlation. Measurement scales. Statistical significance. Distributions. Normality assumption.

Advanced Statistics
Overview of advanced concepts in statistics. Anova. Linear regression. Estimation and hypothesis testing. Error terms.

Introducing Newt
Introducing the basic functionality of the Newt application. Creating sheets. Charts. Menus and Toolbars. Importing data. Saving data in various formats. Exporting data. Shortcuts. List of methods.

Charts
Working with charts. 2D charts. 3D charts. Bar, line, box, pie, range charts. Scatterplots. Histograms.

Predicting values
Time series and forecasting. Trend Analysis. Seasonality. Moving averages. Univariate methods. Multivariate methods. Holt-Winters smoothing. Exponential smoothing. ARIMA. Fourier analysis.

Neural networks
Overview of neural networks. Biology behind neural networks. Basic artificial Model. Training. Preprocessing. Postprocessing. Types of neural networks.

Glossary
Terms and definitions in statistics.

wxpython widgets wx.html.HtmlWindow

wxpython widgets wx.html.HtmlWindow

The wx.html.HtmlWindow widget displays HTML pages. It is not a full-fledged browser. We can do interesting things with wx.html.HtmlWindow widget.
 
import wx
import wx.html as html

ID_CLOSE = 1

page = ' \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
  Maximum  9000
  Mean  6076
  Minimum  3800
  Median  6000
  Standard Deviation  6076
' class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(400, 290)) panel = wx.Panel(self, -1) vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) htmlwin = html.HtmlWindow(panel, -1, style=wx.NO_BORDER) htmlwin.SetBackgroundColour(wx.RED) htmlwin.SetStandardFonts() htmlwin.SetPage(page) vbox.Add((-1, 10), 0) vbox.Add(htmlwin, 1, wx.EXPAND | wx.ALL, 9) bitmap = wx.StaticBitmap(panel, -1, wx.Bitmap('img/sales.png')) hbox.Add(bitmap, 1, wx.LEFT | wx.BOTTOM | wx.TOP, 10) buttonOk = wx.Button(panel, ID_CLOSE, 'Ok') self.Bind(wx.EVT_BUTTON, self.OnClose, id=ID_CLOSE) hbox.Add((100, -1), 1, wx.EXPAND | wx.ALIGN_RIGHT) hbox.Add(buttonOk, flag=wx.TOP | wx.BOTTOM | wx.RIGHT, border=10) vbox.Add(hbox, 0, wx.EXPAND) panel.SetSizer(vbox) self.Centre() self.Show(True) def OnClose(self, event): self.Close() app = wx.App(0) MyFrame(None, -1, 'Basic Statistics') app.MainLoop()

Java Swing


Java Swing

Swing is the principal GUI toolkit for the Java programming language. It is a part of the JFC (Java Foundation Classes), which is an API for providing a graphical user interface for Java programs. It is completely written in Java.
 
package com.tutorial101;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class SimpleEx extends JFrame {

    public SimpleEx() {

        initUI();
    }

    private void initUI() {
        
        setTitle("Simple example"); //window title
        setSize(300, 200); //size window
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() { //This method will close the window if we click on the close button of the titlebar
        
            @Override
            public void run() {
                SimpleEx ex = new SimpleEx();
                ex.setVisible(true);
            }
        });
    }
}

Saturday, June 4, 2016

wxpython advance widgets wx.ListBox

wxpython advance widgets wx.ListBox

A wx.ListBox widget is used for displaying and working with a list of items
 
import wx

ID_NEW = 1
ID_RENAME = 2
ID_CLEAR = 3
ID_DELETE = 4


class ListBox(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 220))

        panel = wx.Panel(self, -1)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.listbox = wx.ListBox(panel, -1) #create an empty wx.ListBox
        hbox.Add(self.listbox, 1, wx.EXPAND | wx.ALL, 20) # put a 20px border around the listbox

        btnPanel = wx.Panel(panel, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        new = wx.Button(btnPanel, ID_NEW, 'New', size=(90, 30))
        ren = wx.Button(btnPanel, ID_RENAME, 'Rename', size=(90, 30))
        dlt = wx.Button(btnPanel, ID_DELETE, 'Delete', size=(90, 30))
        clr = wx.Button(btnPanel, ID_CLEAR, 'Clear', size=(90, 30))

        self.Bind(wx.EVT_BUTTON, self.NewItem, id=ID_NEW)
        self.Bind(wx.EVT_BUTTON, self.OnRename, id=ID_RENAME)
        self.Bind(wx.EVT_BUTTON, self.OnDelete, id=ID_DELETE)
        self.Bind(wx.EVT_BUTTON, self.OnClear, id=ID_CLEAR)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnRename) #bind a wx.EVT_COMMAND_LISTBOX_DOUBLE_CLICKED event type with the OnRename() method

        vbox.Add((-1, 20))
        vbox.Add(new)
        vbox.Add(ren, 0, wx.TOP, 5)
        vbox.Add(dlt, 0, wx.TOP, 5)
        vbox.Add(clr, 0, wx.TOP, 5)

        btnPanel.SetSizer(vbox)
        hbox.Add(btnPanel, 0.6, wx.EXPAND | wx.RIGHT, 20)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

    def NewItem(self, event):
        text = wx.GetTextFromUser('Enter a new item', 'Insert dialog')
        if text != '':
            self.listbox.Append(text)

    def OnRename(self, event):
        sel = self.listbox.GetSelection()
        text = self.listbox.GetString(sel)
        renamed = wx.GetTextFromUser('Rename item', 'Rename dialog', text)
        if renamed != '':
            self.listbox.Delete(sel)
            self.listbox.Insert(renamed, sel)


    def OnDelete(self, event):
        sel = self.listbox.GetSelection()
        if sel != -1:
            self.listbox.Delete(sel)

    def OnClear(self, event):
        self.listbox.Clear()


app = wx.App()
ListBox(None, -1, 'ListBox')
app.MainLoop()

wxpython widgets wx.SpinCtrl

wxpython widgets wx.SpinCtrl

The wx.SpinCtrl widget lets us increment and decrement a value. It has two up and down arrow buttons for this purpose. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        
        wx.StaticText(self, label='Convert Fahrenheit temperature to Celsius', 
            pos=(20,20))
        wx.StaticText(self, label='Fahrenheit: ', pos=(20, 80))
        wx.StaticText(self, label='Celsius: ', pos=(20, 150))
        
        self.celsius = wx.StaticText(self, label='', pos=(150, 150))
        self.sc = wx.SpinCtrl(self, value='0', pos=(150, 75), size=(60, -1))
        self.sc.SetRange(-459, 1000)
        
        btn = wx.Button(self, label='Compute', pos=(70, 230))
        btn.SetFocus()
        cbtn = wx.Button(self, label='Close', pos=(185, 230))

        btn.Bind(wx.EVT_BUTTON, self.OnCompute)
        cbtn.Bind(wx.EVT_BUTTON, self.OnClose)
           
        self.SetSize((350, 310))
        self.SetTitle('wx.SpinCtrl')
        self.Centre()
        self.Show(True)          
        
    def OnClose(self, e):
        
        self.Close(True)    
        
    def OnCompute(self, e):
        
        fahr = self.sc.GetValue()
        cels = round((fahr - 32) * 5 / 9.0, 2)
        self.celsius.SetLabel(str(cels))        
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.Slider

wxpython widgets wx.Slider

wx.Slider is a widget that has a simple handle. This handle can be pulled back and forth. This way we can choose a specific task.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        sld = wx.Slider(pnl, value=200, minValue=150, maxValue=500, pos=(20, 20), 
            size=(250, -1), style=wx.SL_HORIZONTAL)
        
        sld.Bind(wx.EVT_SCROLL, self.OnSliderScroll)
        
        self.txt = wx.StaticText(pnl, label='200', pos=(20, 90))               
        
        self.SetSize((290, 200))
        self.SetTitle('wx.Slider')
        self.Centre()
        self.Show(True)    

    def OnSliderScroll(self, e):
        
        obj = e.GetEventObject()
        val = obj.GetValue()
        
        self.txt.SetLabel(str(val))        

                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.Gauge

wxpython widgets wx.Gauge

wx.Gauge is a widget that is used, when we process lengthy tasks. It has an indicator to show the current state of a task.
 
import wx

TASK_RANGE = 50

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   
        
        self.timer = wx.Timer(self, 1)
        self.count = 0

        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)

        self.gauge = wx.Gauge(pnl, range=TASK_RANGE, size=(250, 25))
        self.btn1 = wx.Button(pnl, wx.ID_OK)
        self.btn2 = wx.Button(pnl, wx.ID_STOP)
        self.text = wx.StaticText(pnl, label='Task to be done')

        self.Bind(wx.EVT_BUTTON, self.OnOk, self.btn1)
        self.Bind(wx.EVT_BUTTON, self.OnStop, self.btn2)

        hbox1.Add(self.gauge, proportion=1, flag=wx.ALIGN_CENTRE)
        hbox2.Add(self.btn1, proportion=1, flag=wx.RIGHT, border=10)
        hbox2.Add(self.btn2, proportion=1)
        hbox3.Add(self.text, proportion=1)
        vbox.Add((0, 30))
        vbox.Add(hbox1, flag=wx.ALIGN_CENTRE)
        vbox.Add((0, 20))
        vbox.Add(hbox2, proportion=1, flag=wx.ALIGN_CENTRE)
        vbox.Add(hbox3, proportion=1, flag=wx.ALIGN_CENTRE)

        pnl.SetSizer(vbox)
        
        self.SetSize((300, 200))
        self.SetTitle('wx.Gauge')
        self.Centre()
        self.Show(True)     

    def OnOk(self, e):
        
        if self.count >= TASK_RANGE:
            return

        self.timer.Start(100)
        self.text.SetLabel('Task in Progress')

    def OnStop(self, e):
        
        if self.count == 0 or self.count >= TASK_RANGE or not self.timer.IsRunning():
            return

        self.timer.Stop()
        self.text.SetLabel('Task Interrupted')
        
    def OnTimer(self, e):
        
        self.count = self.count + 1
        self.gauge.SetValue(self.count)
        
        if self.count == TASK_RANGE:

            self.timer.Stop()
            self.text.SetLabel('Task Completed')
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()    

wxpython widgets wx.RadioButton

wxpython widgets wx.RadioButton

wx.RadioButton is a widget that allows the user to select a single exclusive choice from a group of options.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   
            
        pnl = wx.Panel(self)

        self.rb1 = wx.RadioButton(pnl, label='Value A', pos=(10, 10), 
            style=wx.RB_GROUP)
        self.rb2 = wx.RadioButton(pnl, label='Value B', pos=(10, 30))
        self.rb3 = wx.RadioButton(pnl, label='Value C', pos=(10, 50))
        
        self.rb1.Bind(wx.EVT_RADIOBUTTON, self.SetVal)
        self.rb2.Bind(wx.EVT_RADIOBUTTON, self.SetVal)
        self.rb3.Bind(wx.EVT_RADIOBUTTON, self.SetVal)

        self.sb = self.CreateStatusBar(3)
        
        self.sb.SetStatusText("True", 0)
        self.sb.SetStatusText("False", 1)
        self.sb.SetStatusText("False", 2)   

        self.SetSize((210, 210))
        self.SetTitle('wx.RadioButton')
        self.Centre()
        self.Show(True)     

    def SetVal(self, e):
        
        state1 = str(self.rb1.GetValue())
        state2 = str(self.rb2.GetValue())
        state3 = str(self.rb3.GetValue())

        self.sb.SetStatusText(state1, 0)
        self.sb.SetStatusText(state2, 1)
        self.sb.SetStatusText(state3, 2)            
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()  

wxpython widgets wx.StatusBar

wxpython widgets wx.StatusBar

wx.StatusBar widget is used to display application status information.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        button = wx.Button(pnl, label='Button', pos=(20, 20))
        text = wx.CheckBox(pnl, label='CheckBox', pos=(20, 90))
        combo = wx.ComboBox(pnl, pos=(120, 22), choices=['Python', 'Ruby'])
        slider = wx.Slider(pnl, 5, 6, 1, 10, (120, 90), (110, -1))        

        pnl.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        button.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        text.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        combo.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        slider.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)

        self.sb = self.CreateStatusBar()

        self.SetSize((250, 230))
        self.SetTitle('wx.Statusbar')
        self.Centre()
        self.Show(True)     

    def OnWidgetEnter(self, e):
        
        name = e.GetEventObject().GetClassName()
        self.sb.SetStatusText(name + ' widget')
        e.Skip()               
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main() 

wxpython widgets wx.CheckBox

wxpython widgets wx.CheckBox

wx.CheckBox is a widget that has two states: on and off. It is a box with a label. The label can be set to the right or to the left of the box. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        cb = wx.CheckBox(pnl, label='Show title', pos=(20, 20))
        cb.SetValue(True) #constructor of the wx.CheckBox widget

        cb.Bind(wx.EVT_CHECKBOX, self.ShowOrHideTitle)

        self.SetSize((250, 170))
        self.SetTitle('wx.CheckBox')
        self.Centre()
        self.Show(True)    

    def ShowOrHideTitle(self, e):
        
        sender = e.GetEventObject()
        isChecked = sender.GetValue()
        
        if isChecked:
            self.SetTitle('wx.CheckBox')            
        else: 
            self.SetTitle('')        
                       
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

wxpython widgets wx.ComboBox

wxpython widgets wx.ComboBox 

wx.ComboBox is a combination of a single line text field, a button with a down arrow image and a listbox. When you press the button, a listbox appears.
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)
        
        distros = ['Ubuntu', 'Arch', 'Fedora', 'Debian', 'Mint']
        cb = wx.ComboBox(pnl, pos=(50, 30), choices=distros, 
            style=wx.CB_READONLY)

        self.st = wx.StaticText(pnl, label='', pos=(50, 140))
        cb.Bind(wx.EVT_COMBOBOX, self.OnSelect)
        
        self.SetSize((250, 230))
        self.SetTitle('wx.ComboBox')
        self.Centre()
        self.Show(True)          
        
    def OnSelect(self, e):
        
        i = e.GetString()
        self.st.SetLabel(i)
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()  

wxpython widgets wx.StaticBox

wxpython widgets wx.StaticBox

This is a kind of a decorator widget. It is used to logically group various widgets.  
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)
        
        wx.StaticBox(pnl, label='Personal Info', pos=(5, 5), size=(240, 170))
        wx.CheckBox(pnl, label='Male', pos=(15, 30))
        wx.CheckBox(pnl, label='Married', pos=(15, 55))
        wx.StaticText(pnl, label='Age', pos=(15, 95))
        wx.SpinCtrl(pnl, value='1', pos=(55, 90), size=(60, -1), min=1, max=120)
        
        btn = wx.Button(pnl, label='Ok', pos=(90, 185), size=(60, -1))

        btn.Bind(wx.EVT_BUTTON, self.OnClose)

        self.SetSize((270, 250))
        self.SetTitle('Static box')
        self.Centre()
        self.Show(True)          
        
    def OnClose(self, e):
        
        self.Close(True)    
               
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()   

wxpython widgets wx.StaticText

wxpython widgets wx.StaticText

A wx.StaticText widget displays one or more lines of read-only text.

 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        txt1 = '''I'm giving up the ghost of love
in the shadows cast on devotion
She is the one that I adore
creed of my silent suffocation
Break this bittersweet spell on me
lost in the arms of destiny'''

        txt2 = '''There is something in the way
You're always somewhere else
Feelings have deserted me
To a point of no return
I don't believe in God
But I pray for you'''

        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        st1 = wx.StaticText(pnl, label=txt1, style=wx.ALIGN_CENTRE)
        st2 = wx.StaticText(pnl, label=txt2, style=wx.ALIGN_CENTRE)
        
        vbox.Add(st1, flag=wx.ALL, border=5)
        vbox.Add(st2, flag=wx.ALL, border=5)
        pnl.SetSizer(vbox)
        
        self.SetSize((250, 260))
        self.SetTitle('Bittersweet')
        self.Centre()
        self.Show(True)          
                        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

Related Post