python logo


Tag: GUI

Tk window and button

Tk button with onClick event
To create a Tkinter window with a button use the example below. The program enters mainloop() which wait for events (user actions). We define the button which has a callback to the function callback(). master is the root window, the window where your button will appear in.

from Tkinter import *

master = Tk()

def callback():
print "click!"

b = Button(master, text="OK", command=callback)
b.pack()

mainloop()
tk button tk button

Related course

Tk image button
If you want an image button, use the PhotoImage class. We set the size of the window and the miminum size with the functions minsize() and geometry(). Example:

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, command=callback, height=50, width=150)
b.pack()

mainloop()

Result:

tk image button tk image button

Tk Image button with text label
If you want both an image and text, simply add the parameter compound=LEFT.

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.pack()

mainloop()

Result:

tk button with text and image tk button with text and image

Button location
If you want to place the button on your coordinates do not use the pack() function but instead use the function place(x,y), as shown in the example below:

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.place(x = 20, y = 20)

mainloop()

Result:

tk button location tk button location

If you are new to programming Tkinter, I highly recommend this course.

download tkinter examples

QT4 Messagebox

PyQT4 offers message box functionality using several functions.
Messageboxes included in PyQT4 are: question, warning, error, information, criticial and about box.

Related course: Create GUI Apps with Python PyQt5

PyQt4 mesagebox

The code below will display a message box with two buttons:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')

# Show window
w.show()

sys.exit(a.exec_())

Result:

qtMessagebox question qtMessagebox question

There are different types of messageboxes that PyQT4 provides.

PyQT4 Warning Box


You can display a warning box using this line of code:

QMessageBox.warning(w, "Message", "Are you sure you want to continue?")

PyQT4 Information box


We can display an information box using QMessageBox.information()

QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")

Result:

QMessageBox Info QMessageBox Info

PyQT4 Critical Box


If something goes wrong in your application you may want to display an error message.

QMessageBox.critical(w, "Message", "No disk space left on device.")



Result:

QMessagebox QMessagebox

PyQT4 About box


We have shown the question box above.

QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")



Result:

qt Messagebox qt Messagebox

Download PyQT Code (Bulk Collection)

Introduction to GUI

To create a graphical interface (GUI) in Python you need to make use of a library or module.  There are at least three widely used modules for creating GUIs with Python:

While you can create a graphical user interface (GUI) with any of these modules, they do not have the same features.

Related course:

GUI toolkits


Tk provides basic widgets such as a button, menu, text and label. It is very limited compared to QT4 and WxPython but it is also the oldest module.  It runs on most versions of Mac OS, Linux and Windows.

TkMessage box a messagebox in Tk. GUIs made in Tk do not have a native look.

QT4 and QT5 are developed by the Qt company.  Graphical applications made with QT4 or QT5 run on Windows, Linux/X11 and Mac OS X.  It has tons of widgets including tabs, buttons, item views, table views, progressbars, input fields, calendar views and many more. Compared to Tk it has a lot more widgets available.

Graphical application using PyQt5

WxPython is a module that creates a native GUI look regardless of the operating system used. On Windows it will look as windows application while on Mac OS it will look as a Mac application. This can be a clear advantage compared to QT4 or Tk, depending on your purpose. WxWidgets has many widgets available such as buttons, menu, text but also more advanced widgets as a htmlview or tree control.

wxTabs A window created with wxPython. wxPython has native appearance on all operating systems.

wxPython window

wxPython is a GUI toolkit for the Python programming language. wxPython can be used to create graphical user interfaces (GUI).

Applications made with wxPython have a native appearance on all platforms. The application will appear as native application unlike QT or Tk which have a custom QT or Tk look. It runs on all major desktop platforms.

Currently supported operating systems are Microsoft Windows (32-bit), most Unix or unix-like systems, and Macintosh OS X.

Related course: Creating GUI Applications with wxPython

The wxPython module is based on the C++ GUI library wxWidgets.

wxPython window


To open a window with wxPython, run the code below:

#!/usr/bin/python

import wx
app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.Show()
app.MainLoop()

The line wx.App() creates an application object. Each wx program needs to have one .App() object.

The method wx.Frame() returns a new window which can contain widgets.

app.Mainloop() puts the application in the main loop and listens for events.

Window size and position
You can set the position and size with the SetDimensions() function:

#!/usr/bin/python

import wx

app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,640,480)
frame.Show()
app.MainLoop()

The parameters of the function are: x (left), y (top), width and height. The function not only sets the screen resolution but also the position on the screen.

Center a window
To put the window in the center of the screen call:

frame.Centre()

Related course: Creating GUI Applications with wxPython
 

wxPython file dialog

Nearly every desktop application that can open one or more files has a file dialog.

An open file dialog may seem like a very complicated window to create: it contains buttons, locations, labels and many more widgets. Moreover, the appearance of this open file dialog looks different on every platform: Mac OS, Windows and so on.

Related course: Creating GUI Applications with wxPython

The wxPython module comes with open file dialogs, which can be created with a few functions calls.

wxPythonOpenFile wxPython Open File Dialog

wxPython file dialog


The example below creates a file dialog with a native appearance using wxPython:

#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()

frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

# Create open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "",
"Python files (*.py)|*.py",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

openFileDialog.ShowModal()
print(openFileDialog.GetPath())
openFileDialog.Destroy()

To create a file dialog with wxPython we can simply call wx.FileDialog().
The definition of this method is: (parent, message, defaultDir, defaultFile, wildcard, style, pos)
We call this method with the arguments:


wx.FileDialog(frame, "Open", "", "","Python files (*.py)|*.py",wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

(no default dir or default file is specified).

The method showModal() displays the window:


openFileDialog.ShowModal()

The command openFileDialog.GetPath() returns the full path to the file if one is selected.

Related course: Creating GUI Applications with wxPython

Tk menubar - Menus in Tkinter

The Tkinter toolkit comes with all the basic widgets to create graphical applications. Almost every app has a main menu. As expected, Tkinter supports adding a main menu to your application window.

The screenshot below demonstrates a Tkinter based menu:

tk menu Tkinter menu

Related course

Tkinter menubar


You can create a simle menu with Tkinter using the code below. Every option (new, open, save.. ) should have its own callback.

from Tkinter import *

def donothing():
x = 0

root = Tk()

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)
root.mainloop()

We create the menubar with the call:


menubar = Menu(root)

where root is a Tk() object.

A menubar may contain zero or more submenus such as the file menu, edit menu, view menu, tools menu etcetera.

A submenu can be created using the same Menu() call, where the first argument is the menubar to attach to.


filemenu = Menu(menubar, tearoff=0)
menu = Menu(menubar, tearoff=0)

Individual options can be added to these submenus using the add_command() method:


filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)

In the example we created the callback function donothing() and linked every command to it for simplicity. An option is added using the add_comment() function. We call add_cascade() to add this menu list to the specific list.

If you are new to programming Tkinter, I highly recommend this course.

download tkinter examples

Tk widgets - Tkinter widgets in Python

Tkinter has several widgets including:


  • Label

  • EditText

  • Images

  • Buttons (Discussed before)

In this article we will show how to use some of these Tkinter widgets. Keep in mind there’s a slight difference between Tkinter for Python 2.x and 3.x

Related course

Label
To create a label we simply call the Label() class and pack it. The numbers padx and pady are the horizontal and vertical padding.

from Tkinter import *

root = Tk()
root.title('Python Tk Examples @ pythonspot.com')
Label(root, text='Python').pack(pady=20,padx=50)

root.mainloop()

EditText (Entry widget)
To get user input you can use an Entry widget.

from Tkinter import *

root = Tk()
root.title('Python Tk Examples @ pythonspot.com')

var = StringVar()
textbox = Entry(root, textvariable=var)
textbox.focus_set()
textbox.pack(pady=10, padx=10)

root.mainloop()

Result:

tk entry tk entry

Images
Tk has a widget to display an image, the PhotoImage. It is quite easy to load an image:

from Tkinter import *
import os

root = Tk()
img = PhotoImage(file="logo2.png")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

Result:

python tk image python tk image

If you are new to programming Tkinter, I highly recommend this course.

GUI editor
An overview of Tkinter GUI editors can be found here: http://wiki.tcl.tk/4056

download tkinter examples

TkInter message box

The Tkinter tkMessageBox has various methods to display a message box.

There is a slight difference between Tkinter for Python 2.7 and Python 3.
To find your Python version try one of these commands:

python --version
python3 --version

Related courses

Tkinter Message box

Tkinter Message box TkMessage boxTo show a minimalistic Tkinter message box, use the function showinfo() where the parameters are the window title and text.

The showinfo() function is in a different module depending on the Python version.

Python 3.x

from tkinter import messagebox

messagebox.showinfo("Title", "a Tk MessageBox")


Python 2.7

import Tkinter
import tkMessageBox

tkMessageBox.showinfo("Title", "a Tk MessageBox")


Tkinter showerror, showwarning and showinfo


tkinter-dialog Tk messagebox dialog

Tkinter includes several other message boxes:

  • showerror()
  • showwarning()
  • showinfo()

Python 3.x

import tkinter
from tkinter import messagebox

# hide main window
root = tkinter.Tk()
root.withdraw()

# message box display
messagebox.showerror("Error", "Error message")
messagebox.showwarning("Warning","Warning message")
messagebox.showinfo("Information","Informative message")

Python 2.7

import Tkinter
import tkMessageBox

# An error box
tkMessageBox.showerror("Error","No disk space left on device")

# A warning box
tkMessageBox.showwarning("Warning","Could not start service")

# An information box
tkMessageBox.showinfo("Information","Created in Python.")


You may like: Tkinter Question Dialog or More Tkinter

If you are new to programming Tkinter, I highly recommend this course.

download tkinter examples

Menu with PyQt4

PyQT Menu pythonspot PyQT Menu

PyQt4 menus appear in the top of the window bar. A menu gives the user control over the application and is often location in the top of the window.

The QMainWindow class creates the main application window. This class has a method named menuBar() which adds the title bar.

Menus can be added to the title bar using addMenu(). Inside each menu you can add a command using the addAction method.

Related course:

PyQt4 menubar


This code will add a menu to your qt4 app:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Create main menu
mainMenu = w.menuBar()
mainMenu.setNativeMenuBar(False)
fileMenu = mainMenu.addMenu('&File')

# Add exit button
exitButton = QAction(QIcon('exit24.png'), 'Exit', w)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(w.close)
fileMenu.addAction(exitButton)

# Show window
w.show()

sys.exit(a.exec_())

Download PyQT Code (Bulk Collection)

QT4 Table

We can show a table using the QTableWidget, part of the PyQt module.  We set the title, row count, column count and add the data.

Related course:

Qt4 Table example


An example below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQt Table

QTableWidget labels


You can set the header using the setHorizontalHeaderLabels() function. The same applies for vertical labels. A demonstration below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQT Table

QTableWidget click events


We can detect cell clicks using this procedure, first add a function:

# on click function
table.cellClicked.connect(cellClick)



Then define the function:

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

The Python programming language starts counting with 0, so when you press on (1,1) you will see (0,0). Full code to detect table clicks:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# on click function
table.cellClicked.connect(cellClick)

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

If you want to show the cell/row numbers in a non-programmer way use this instead:

def cellClick(row,col):
print "Click on " + str(row+1) + " " + str(col+1)



Tooltip text


We can set tooltip (mouse over) text using the method. If you set tooltips on non-existing columns you will get an error.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# tooltip text
table.horizontalHeaderItem(0).setToolTip("Column 1 ")
table.horizontalHeaderItem(1).setToolTip("Column 2 ")

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table tooltips PyQT Table tooltips

Download PyQT Code (Bulk Collection)

QT4 Tabs

Tabs are very useful in graphical applications. They appear in webbrowsers, text editors and any other apps.  To create a tabbed window, you need to call the  QTabWidget()  function.  Every tab is a QWidget() which you have seen before.  You can connect the QWidgets with the QTabWidget with the function:

tabs.addTab(tab1,"Tab 1")

where the first parameter is the tab object and the second the name that appears on the screen. We added some buttons to the first tab (QWidget).

Related course:

Example code:

from PyQt4 import QtGui
from PyQt4 import QtCore
import sys

def main():

app = QtGui.QApplication(sys.argv)
tabs = QtGui.QTabWidget()

# Create tabs
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()

# Resize width and height
tabs.resize(250, 150)

# Set layout of first tab
vBoxlayout = QtGui.QVBoxLayout()
pushButton1 = QtGui.QPushButton("Start")
pushButton2 = QtGui.QPushButton("Settings")
pushButton3 = QtGui.QPushButton("Stop")
vBoxlayout.addWidget(pushButton1)
vBoxlayout.addWidget(pushButton2)
vBoxlayout.addWidget(pushButton3)
tab1.setLayout(vBoxlayout)

# Add tabs
tabs.addTab(tab1,"Tab 1")
tabs.addTab(tab2,"Tab 2")
tabs.addTab(tab3,"Tab 3")
tabs.addTab(tab4,"Tab 4")

# Set title and show
tabs.setWindowTitle('PyQt QTabWidget @ pythonspot.com')
tabs.show()

sys.exit(app.exec_())

if __name__ == '__main__':
main()

Result:

PyQT Tabs PyQT Tabs

Download PyQT Code (Bulk Collection)

QT4 Pixmaps (Images)

In this article we will demonstrate how to load and display images in an PyQT window. We can display images in a PyQT window using the Pixmap widget.

PyQt4-load-image An image loaded in a PyQt4 window.

Related course:

Introduction


The constructor of Pixmap takes the image path as parameter:

pixmap = QPixmap(os.getcwd() + '/logo.png')

This image needs to be in the same directory as your program. The QPixmap widget supports png and jpeg.  Example code below.

PyQT load image in Pixmap


We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.

import os
import sys
from PyQt4.QtGui import *

# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")

# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())

# Draw window
w.show()
app.exec_()

Download PyQT Code (Bulk Collection)

Result:

pyqt Pixmap pyqt Pixmap

QT4 Progressbar

In this article we will demonstrate how to use the progressbar widget.  The progressbar is different from the other widgets in that it updates in time.

Related course:

QT4 Progressbar Example
Let’s start with the code:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT

class QProgBar(QProgressBar):

value = 0

@pyqtSlot()
def increaseValue(progressBar):
progressBar.setValue(progressBar.value)
progressBar.value = progressBar.value+1

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("PyQT4 Progressbar @ pythonspot.com ")

# Create progressBar.
bar = QProgBar(w)
bar.resize(320,50)
bar.setValue(0)
bar.move(0,20)

# create timer for progressBar
timer = QTimer()
bar.connect(timer,SIGNAL("timeout()"),bar,SLOT("increaseValue()"))
timer.start(400)

# Show window
w.show()

sys.exit(a.exec_())

The instance bar (of class QProgBar) is used to hold the value of the progressbar.  We call the function setValue() to update its value.  The parameter w is given to attach it to the main window. We then move it to position (0,20) on the screen and give it a width and height.

To update the progressbar in time we need a QTimer().  We connect the widget with the timer, which calls the function increaseValue().  We set the timer to repeat the function call every 400 milliseconds.  You also see the words SLOT and SIGNAL.  If a user does an action such as clicking on a button, typing text in a box - the widget sends out a signal.  This signal does nothing, but it can be used to connect with a slot, that acts as a receiver and acts on it.

Result:

PyQT Progressbar PyQT Progressbar

Download PyQT Code (Bulk Collection)

QML and PyQT: Creating a GUI (tutorial)

If you have not done our first PyQT tutorial yet, you should do it, it’s fun! In this tutorial we will use PyQT4 and a user interface markup language, a language that describes the graphical  user interfaces and controls

Related course:

QML and PyQT


An excerpt of user interface markup graphical user interfaces and language code could look like:

 Rectangle {
id: simplebutton
color: "grey"
width: 150; height: 75

Essentially the language tells what the interface should look like. The language we will be using is called QML.

QTCreator


Start a programmed called QTCreator.   The tutorial will be quite graphical to help you through the whole process. Simply type qtcreator in the terminal or start it from the menu list.  This screen should pop up:

qtcreator qtcreator

Creating a GUI


Press the big New Project button. Select QT Quick Application from the menu below. Finally press Choose on the bottom right.

qtquick qtquick

A new popup will appear:

kde create kde create

Type a name and a valid path to save your project. Then press Next.  Select QT Quick 2.0 from the menu list. Press Next. Press Finish. Immediately a user interface defined in the QML language will appear.

qt quick qt quick

Like all great programmers we are going to solve things the most lazy way possible.  Instead of typing all the QML code by hand we are going to press the Design button that is on the left of the screen.  A drag and drop screen should appear now.

draganddrop draganddrop

We drag an image onto the area and select the source on the right. Save the project. Open a terminal and locate the qml file you just created. Alternatively you could simply copy the code in the edit box and save it to a .qml file. Enter the command:

qmlviewer main.qml

This will display the windows as defined in the qml file without any functionality. It is simply a viewer for the interface.  We then create some code to load this QML definition:

import sys

from PyQt4.QtCore import QDateTime, QObject, QUrl, pyqtSignal
from PyQt4.QtGui import QApplication
from PyQt4.QtDeclarative import QDeclarativeView

app = QApplication(sys.argv)

# Create the QML user interface.
view = QDeclarativeView()
view.setSource(QUrl('main.qml'))
view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.setGeometry(100, 100, 400, 240)
view.show()

app.exec_()

Finally we modify the first line main.qml to:

import Qt 4.7

Simply because our QtQuick was missing. Running

python run.py

Will now display our user interface as defined by QML:

QML_PyQT QML and PyQT

All of the code is simply PyQT, so you could add code like in the previous tutorial. These are the two methods to create a graphical interface with PyQT.  This method may be more loosely coupled to the code compared to the method of creating a GUI with QT in the previous tutorial. Despite that both are valid methods.

Download PyQT4 Examples (Bulk Collection)

You may like: Application GUI with PyQT4 or the PyQt4 Tutorials

wxPython GUI tutorial

wxPython GUI wxPython GUI The wxPython module can be used to create a graphical application (GUI) that looks like a native application on any operating system including Windows, Mac OS X and Linux.

The official wxPython site has several screenshots and downloads for these platforms. wxPython is based on wxWidgets.

Related course: Creating GUI Applications with wxPython

Install wxPython

First download and install WxPython, the Python bindings for wxWidgets.

sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-doc wx2.8-examples wx2.8-headers wx2.8-i18n


Then install a GUI creator called wxglade:

sudo apt-get install wxglade


Using a GUI builder such as wxGlade will save you a lot of time, regardless of the GUI library you use. You can easily make complex graphical interfaces because you can simply drag and drop.

Creating our first GUI with Python and wxWidgets:



Start wxglade. You will see its user interface:

wxglade wxglade

Press on tiny window on the top left, below the file icon.

wxglade wxglade

Press OK. An empty window will now appear. Press on the tiny [OK] button in the wxGlade panel and press on the frame. The button will now appear. Press on Application in the tree window.

wxglade wxglade

Set the output file in the wxproperties window.

wxglade wxglade

If you look at the window note you can select multiple programming languages and two versions of wxWidgets. Select Python and wxWidgets 2.8. Finally press Generate code. (Do NOT name the file wx.py because the import needs wx, save it as window.py or something else).

Running wxglade code:


Run:

python window.py

And a window with a button will appear. Pressing the button will not do anything. To start a function when pressing the button, we need to define a so called Callback. This can be as simple as:

def OnButton(self, Event, button_label):
print "In OnButton:", button_label

Finally we bind the button to the callback function using:

self.button_1.Bind(wx.EVT_BUTTON, self.OnButton )

Pressing the button will now write a message to the command line. Instead of the boring command line message, we want to show a message box. This can be done using this command:

wx.MessageBox( "This is a message.", "Button pressed.");

wxPython example code


The full code below:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.6.8 on Fri Jan 23 22:59:56 2015
#

import wx

# begin wxGlade: dependencies
import gettext
# end wxGlade

# begin wxGlade: extracode
# end wxGlade


class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.button_1 = wx.Button(self, wx.ID_ANY, _("Hello World!"))
self.button_1.Bind(wx.EVT_BUTTON, self.OnButton )

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle(_("wxWidgets button example. pythonspot.com "))
# end wxGlade

def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.button_1, 0, 0, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade

def OnButton(event, button_label):
wx.MessageBox( "This is a message.", "Button pressed.");


# end of class MyFrame
if __name__ == "__main__":
gettext.install("app") # replace with the appropriate catalog name

app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, wx.ID_ANY, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()

Related course: Creating GUI Applications with wxPython