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
Python Desktop Apps with Tkinter

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

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:
PyQt Desktop Apps with Python

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:
PyQt Desktop Apps with Python

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.

You can view screenshots of applications made 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()

 

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.

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.

Tk menubar

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
Python Desktop Apps with Tkinter

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.

Posts navigation

1 2 3