Tkinter GUI Development in Python
Tkinter GUI Development in Python
Pythonprovidesvariousoptionstodevelopgraphicaluserinterfaces(GUI)throughmany
libraries
1. Tkinter:TkinteristhePythoninterfacefortheTkGUIlibrarythatcomeswith
[Link] studyitindetailinthischapter.
2. wxPython:ThisisafreeandopensourceimplementationinPython
fromthewxWidgetsprogramminginterface.
3. PyQt:ItisalsoaPythoninterfaceforalibrary
popularmulti-platformQtgraphicalinterface.
4. JPython:JPythonisaPythontoolforJava,whichgivesPythonscripts
transparentaccesstoJavaclasslibraries.
Therearemanyothergraphicalinterfacesavailablethatyoucanfindontheinternet.
2-TheTkintergraphiclibrary
[Link],whenitis
combinedwithTkinter,[Link]
providesapowerful,simple,anduser-friendlyobject-orientedinterface.
[Link]
allyouhavetodoisfollowthesesteps:
1. ImporttheTkintermodule.
2. Createthemainwindowofthegraphicalapplicationthroughaninstantiationonthe
classTk.
3. Enterthemaineventlooptoactagainsteachevent
triggeredbytheuser.
Example:creatingasimpleTkinterwindow
# -*- coding: utf-8 -*-
1) - Importing the tkinter library
from tkinter import *
Whatisdisplayedafterexecution:
Tkinter Widgets
TheTkinterlibraryprovidesvariouscontrols,suchasbuttons,labels,andareasof
[Link].
[Link]
mainwidgetsaswellasabriefdescription:
[Link]:TheButtonwidgetallowsyoutocreatebuttonsforyourapplication.
[Link]:theCanvawidgetallowsyoutodrawshapes,suchaslines,ovals,
polygonsandrectangles,inyourapplication.
[Link]:theCheckbuttonwidgetallowsdisplayingacertainnumberofoptionsintheformof
[Link].
[Link]:theEntrywidgetisusedtodisplayasingle-linetextfieldallowing
toacceptauser'svalues.
[Link]:theFramewidgetisusedasacontainerwidgettoorganizeotherwidgets.
widgets.
[Link]:Thelabelwidgetisusedtoprovideacaptionordescriptionforotherwidgets.
canalsocontainimages.
[Link]:TheListboxwidgetisusedtoprovidealistofoptionstoauser.
[Link]:themenubuttonwidgetisusedtodisplaymenusinyourapplication.
[Link]:[Link]
arecontainedinMenubutton.
[Link]:theMessagewidgetisusedtodisplaymultilinetextfieldsallowing
toacceptuservalues.
[Link]:theRadiobuttonwidgetisusedtodisplayanumberofoptionsunder
[Link].
[Link]:theScalewidgetisusedtoprovideasliderwidget.
[Link]:TheScrollbarwidgetorscrollbarisusedtoaddascrollingfeature
scrollingthroughvariouswidgets,suchaslistareas.
TheTextwidgetisusedtodisplaytextovermultiplelines.
[Link]:TheToplevelwidgetisusedtoprovideaseparatewindowcontainer.
[Link]:theSpinboxwidgetisavariantofthestandardTkinterEntrywidget,whichcanbeused
toselectafixednumberofvalues.
[Link]:thePanedWindowwidgetisacontainerthatcanholdanynumberof
shutters,arrangedhorizontallyorvertically.
[Link]:[Link]
likeaninterleaveroracontainerforcomplexwindowarrangements.
[Link]:thismoduleisusedtodisplaymessageboxesinyourapplications.
Toprocessimages,[Link]
asuccessorforkofthePIL(PythonImagingLibrary)[Link]
quicktothedatacontainedinanimage,itisendowedwithamagicalandpowerfulabilityforthe
processingandmanipulationofdifferentimagefileformatssuchasPNG,JPEG,GIF,
TIFFetBMP..
1.2-InstallationofthePillowlibrary
ThePillowslibraryisinstalledinaverysimplewayusingthepiputility:
pip install pillow
2-InsertinganimageusingthePillowlibrary
NowthatthePillowlibraryisinstalled,itcanbeusedtoinsertandmanipulateimages.
[Link],simplyimportitandcreateanimageobjectto
startingfromafile:
# -*- coding: utf-8 -*-
from PIL import Image, ImageTk
Tounderstandwell,wewilladdressthisthroughasimpleexample:
[Link]
Let'sputtheimageinafoldernamedimages
Let'screateapythonfileinthesamedirectoryastheimagesfolderand
let'sputthefollowingcode:
Exampleofimageinsertion
# -*- coding: utf-8 -*-
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
[Link]("Tkinter window")
[Link]("300x200")
Whatisdisplayedafterexecution:
specifyingthedimensionsinpixelsinparentheses:
# -*- coding: utf-8 -*-
Creation of the image object
load= [Link]("images/[Link]")
[Link]
inputcombinationanddrop-downmenu,[Link]
rightarrow,youwillseeadrop-downmenuindicatingallpossiblechoices.
TocreateaComboBoxlist,youneedtofollowthesesteps:
1. ImporttheTkinterlibraryandthettkmodule
2. CreateaPythonlistcontainingtheelementsoftheComboBoxlist.
3. [Link]()
4. Choosetheelementthatisdisplayedbydefault,byindicatingitsindex.
Example
# -*- coding: utf-8 -*-
1) - Importation of necessary modules
import tkinter as tk
from tkinter import ttk
root= [Link]()
[Link]('300x200')
# 2) - create the Python list containing the elements of the Combobox list
listeProduits=["Laptop", ["Printer","Tablet","Smartphone"]
[Link]()
[Link]()
Whatisdisplayedafterexecution:
2–Associeruneactionàlalistecombobox(bindaction)
YouhaveundoubtedlynoticedthatifyouselectanitemfromtheComboboxlist,
noeventoccurs,simplybecausewehavenotassociatedanyactionwiththelist
[Link],wewillshowhowtocreateanactionlinkedtothiscombobox.
2.1-Anactionbinding(bindaction)iscreatedusingthecommand:
[Link]("<<ComboboxSelected>>", action)
2.2-Wecreatetheactionmethod
def action(event):
2.3Finalcodeofthecomboboxlistwithlinkedaction
root= [Link]()
[Link]('300x200')
def action(event):
2) - create the Python list containing the elements of the Combobox list
listeProduits=["Laptop", ["Printer","Tablet","Smartphone"]
[Link]()
[Link]("<<ComboboxSelected>>", action)
[Link]()
FileDialogisamodulewithopenandsavedialogfunctions,whichcanhelpyou
helpimproveyourTkintergraphicalinterfacetoopenorsaveyourfiles.
TheFiledialoguemodulehasthreemainmethods:
1. askopenfilename():displaysadialogboxthataskstoopena
existingfile.
2. asksaveasfilename():displaysadialogboxthatallowsyoutosavea
file
3. askdirectory():displaysadialogboxthataskstoopena
directory.
2-Themethodaskopenfilename
Asweexplainedabove,thismethoddisplaysadialogboxthatasksfor
[Link]
followingparameters:
1. initialdir:allowspointingtoaninitialdirectoryuponopening.
2. title:quipermetdepersonnaliserletitredelaboitededialogue
3. filetypes:whichallowsspecifyingthetypesoffilestoopen
[Link]
from tkinter import filedialog
from tkinter import *
Byexecutingthiscode,wewillseethefollowingdialogboxappearthatpointstotherootofthe
diskC:\
Remark
Youhaveundoubtedlynoticedthatasmallpopupwindowappearswiththedialogbox!
togetridofthislastone,simplyusethemethodwithdraw():
from tkinter import filedialog
from tkinter import *
Tk().withdraw()
filename= [Link](initialdir= "/",title="Select
File
files","*.*"))
print(filename)
3-Themethodasksaveasfilename
Thismethodissimilartothepreviousone,exceptthatitsavesafileinsteadof
openitanditthereforehasexactlythesameparameters.
[Link]
from tkinter import filedialog
from tkinterimport *
Tk().withdraw()
filename= [Link](initialdir= "/",title= Select
file", filetypes= (("png files","*.png"),("jpeg files","*.jpg"),("all
files","*.*"))
print(filename)
4 - The askdirectory method
Aswehavealreadymentioned,thismethodaskstheusertochoosethedirectoryto
[Link],itwillbestoredinavariableoftype
stringthatcontainsthepathtotheselecteddirectory.
[Link]
from tkinter import *
from tkinter import filedialog
Tk().withdraw()
myDirectory= [Link]()
print (myDirectory)
Beforestartingtocode,[Link]
next:
1. libraryrepresentsthesystem'slibrarydirectory(modulesand
Thisdirectorycontainsanemptyfilenamed__init__.pywhichindicatesto
thePythoninterpreterthatitisthedirectoryofamodule.
2. [Link]:representsthesystemlibrarythatwil containallthe
Pythonclassesnecessaryfortheoperationofthesystem.
3. [Link]:[Link]
thefilecontainsverylittlecode,usuallytheinstancesoftheclasses
[Link]
[Link]
2.1Importingthetkinterlibrary
Theeditorwewanttocreatemanipulatesgraphicobjects:windows,buttons,labels,messageboxes.
dialogue…[Link]
Tkinterforthisproject:
from tkinter import *
import os
savedFile= {1:""}
Note:
Thethirdlinewillallowustostorethequeuedobjectsthatdonotfitinaninstance.
class.
2.3-AddingMenus
Tounderstandthemethodofaddingmenus,pleasereviewthetutorial(page18)onthemenus.
Wegostraighttothecodethataddsamethodadd_menu()thatallowsplaying.
the case:
def add_menu(self):
Creation of the menu bar
menuBar = Menu([Link])
2 - Creation of the File menu
menuFichier = Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= File
Creation of the submenus of the File menu
menuFichier.add_command(label="Nouveau", command=[Link])
menuFile.add_command(label="Open", command=[Link])
menuFichier.add_command(label="Enregistrer", command=[Link])
menuFile.add_command(label="Save as"
command=[Link]
menuFichier.add_command(label="Quitter", command= [Link])
[Link](menu= menuBar)
#3 - Creation of the Edition Menu
menuEdition= Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= Edition
menuEdition.add_command(label="Cancel")
menuEdition.add_command(label="Restore")
menuEdition.add_command(label="Copy", command=[Link])
menuEdition.add_command(label="Couper", command= [Link])
menuEdition.add_command(label="Coller", command=[Link])
#4 - Creation of the Tools Menu
menuOutils = Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= Tools
menuTools.add_command(label="Preferences")
Creation of the Help Menu
menuAide = Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= Help
menuAide.add_command(label="A propos")
2.4–Addingcommandsformenus
Sofar,thecreatedmenusarenotfunctional,aswehavenotyetcreatedthem.
commands!Wemustthereforeassociateacommandwitheachmenu:
command= nom_de_la_commande
Wethenneedtocreateanactionforeachorderthathasthesamename:
def command_name():
#action code here
Codeofthemenuactions
#======================================
Definition of menu actions
#======================================
#------------------------------ #
File menu actions
#-------------------------------
def quitter(self):
[Link]()
def new(self):
[Link]("python [Link]")
def fopen(self):
file = [Link]=
[Link](initialdir= "/",title= Select
File", file types = (("Text Files","*.txt"),("all files","*.*")))
fp = open(file, "r")
r = [Link]()
[Link](1.0, r)
# Menu Enregistrer sous
def saveAs(self):
create save dialog
file=[Link]=[Link](initialdir=
"/",title= Save As\ File
Text","*.txt"),("All files","*.*"))
file = file + .txt
Using the dictionary to store the file
savedFile[1] file
f = open(file, "w")
s = [Link]("1.0", END)
[Link](s)
[Link]()
# menu Enregistrer
def save(self):
if(savedFile[1] ==""):
[Link]()
else:
f = open(savedFile[1], "w")
s = [Link]("1.0", END)
[Link](s)
[Link]()
#------------------------------
Editing menu actions
#------------------------------
def copy(self):
[Link].clipboard_clear()
[Link].clipboard_append([Link].selection_get())
def past(self):
[Link](INSERT, [Link].clipboard_get())
def cut(self):
[Link]()
[Link]("[Link]", "[Link]")
Remark
Theactionsassociatedwiththemenusmustbeplacedbeforethefunctionsthatdefinethemenus.
[Link](CodeonPastebin)
# -*- coding: utf-8 -*-
#------------------------------
# Author : Y. DERFOUFI
# Author Title : Professeur Agrégé de mathématiques & Docteur en Math-
Computing
# Compagny : CRMEF OUJDA
#-----------------------------
from tkinter import *
import os
savedFile= {1:""}
#======================================
1 - Main window class
#======================================
class Win:
def __init__(self, master, content):
Main window
[Link] = master
Main Text Widget
[Link]=content
Creation of the tkinter window
def create(self):
[Link]= Tk()
Text Editor
[Link]('700x550')
Method that adds the text area
def add_text(self):
[Link] = Text([Link])
[Link](expand=1, fill='both')
Generation of the main window
def generate(self):
[Link]()
#======================================
2 - Definition of menu actions
#======================================
#------------------------------
2.1 - actions of the File menu
#-------------------------------
def exit(self):
[Link]()
def new(self):
[Link]("python [Link]")
def fopen(self):
file = [Link]=
[Link](initialdir= "/",title= Select
File",filetypes= (("Text Files","*.txt"),("all files","*.*")))
fp = open(file, "r")
r = [Link]()
[Link](1.0, r)
Save As
def saveAs(self):
create save dialog
file=[Link]=[Link](initialdir=
"/",title= Save As\ File
Texte","*.txt"),("Tous les fichiers","*.*")))
file = file + .txt
Using the dictionary to store the file
savedFile[1] file
f = open(file, "w")
s = [Link]("1.0", END)
[Link](s)
[Link]()
# menu Enregistrer
def save(self):
if(savedFile[1] ==""):
[Link]()
else:
f = open(savedFile[1],"w")
s = [Link]("1.0", END)
[Link](s)
[Link]()
#------------------------------
2.2 - Edit menu actions
#------------------------------
def copy(self):
[Link].clipboard_clear()
[Link].clipboard_append([Link].selection_get())
def past(self):
[Link](INSERT, [Link].clipboard_get())
def cut(self):
[Link]()
[Link]("[Link]", "[Link]")
#======================================
2 - Methods for Adding Menus
#======================================
def add_menu(self):
1 - Creation of the menu bar
menuBar = Menu([Link])
2 - Creation of the File menu
menuFichier = Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= File
Creation of submenus in the File menu
menuFichier.add_command(label="Nouveau", command=[Link])
menuFichier.add_command(label="Ouvrir", command=[Link])
menuFichier.add_command(label="Enregistrer", command=[Link])
menuFichier.add_command(label="Enregistrer sous",
command=[Link]
menuFichier.add_command(label="Quitter", command= [Link])
[Link](menu= menuBar)
#3 - Creation of the Edit Menu
menuEdition= Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= Edition
menuEdition.add_command(label="Cancel")
Restore
menuEdition.add_command(label="Copy", command=[Link])
menuEdition.add_command(label="Couper", command= [Link])
menuEdition.add_command(label="Paste", command=[Link])
#4 - Creation of the Tools Menu
menuOutils = Menu(menuBar,tearoff=0)
menuBar.add_cascade(label= Tools
menuTools.add_command(label="Preferences")
Creation of the Help Menu
menuAide = Menu(menuBar, tearoff=0)
menuBar.add_cascade(label= Help
menuHelp.add_command(label='About')
3- Code of the main file [Link] (Code on pastbin)
# -*- coding: utf-8 -*-
Importing the necessary libraries
from tkinter import *
from tkinter import filedialog
Call the methods that create the window object with all its components
[Link]()
root.add_text()
root.add_menu()
[Link]()
4-PublisherOverview
Ifyouhavecodedyoursystemwellandeverythingisgoingwell,hereisanoverviewofyourlittletexteditor:
1– Introduction
DevelopedbyRobinDunnwithHarriPasanen,wxPythonisimplementedasamodule.
[Link]:alibrarywhosemainfunctionis
tocallandquerythemodulesandfunctionsofanotherlibrary:wxWidgets(writteninC++),
apopularmulti-platformgraphicalinterfacetoolkit.
LikeallwxWidgets,[Link].
official[Link]
[Link]
beinstalleddirectlyviathepiputility.
[Link]
classewxObject,quiconstituelabasedetouteslesclassesdel’[Link]ôlecontient
[Link]
example,[Link],[Link],[Link](modifiabletextcontrol),etc.
ThewxPythonAPIhasaGDI(GraphicsDeviceInterface)[Link].
[Link],color,brush,[Link]
[Link],werecommendyoutoseethe
officialdocumentationonthelibrary'swiki:[Link]
2-InstallingwxPythonandfirstprogram
2.1-InstallationofthewxPythonlibrary
ToinstallthewxPythonlibrary,[Link].
cmdandtype:
pip install -U wxPython
2.2– Firstprogram'HelloWorld!'withwxPython
Wewillnowseehowtocreateourfirst'HelloWorld!'windowwithwxPython.
Forthiswemust:
1. ImportthewxPythonlibrary:usingthecommandimportwx
2. CreateanapplicationobjectusingtheApp()method:app=[Link]()
3. Createaframe(frame):frame=[Link]()
4. VisualizetheframeusingtheShow()method:[Link]()
5. ImplementtheapplicationusingtheMainloop()method:[Link]()
Importing the wxPython library.
import wx
Whatdisplaysafterexecution:
2.3Propertiesofaframewindow
AwindowfromthewxPythonlibraryisequippedwithmanyproperties:title,SetSize,
BackgroundColour…
Example.Windowofdimension400×200withagreenbackground
Importing the wxPython library.
import wx
Window properties
[Link]= Hello World!
[Link]= green
[Link](0,0,400,200)
3-wxPythonwidgets
wxPythonhasawiderangeofvariouswidgets,includingbuttons,checkboxes,
cursorsandlistareas.
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
3.1–[Link]
[Link],youneedto:
1. CreateamainframewiththeFrame()method
2. CreateapanelusingthePanel()method
3. Addthebuttontothepanel
3.1.1–Creatingasimplebutton
[Link]
# -*- coding: utf-8 -*-
import wx
app= [Link]()
frame = [Link](None, title='Window with button')
[Link](0,0,350,200)
Create a Panel
panel= [Link](frame)
[Link]()
[Link]()
Thisdisplaysabuttoninthetopleftcornerofthewindow.
Butwecaneasilychangethepositionanddimensionsofthebuttonusingthe
methodSetSize():
[Link](50,50,200,30)
3.1.2–Associateanactionwithacommandbutton
Toassociateanactioneventwithacommandbutton,simplydefinetheeventon
aPythonmethodandlinkittothebuttonusingthebind()method:
[Link](wx.EVT_BUTTON, action)
Example:closebuttonofawindow.
# -*- coding: utf-8 -*-
import wx
def action(event):
[Link]()
app = [Link]()
frame= [Link](None, title='Window with button')
[Link](0,0,350,200)
Create a Panel
panel= [Link](frame)
[Link]()
[Link]()
Byexecutingthecodeabove,wegetthefollowingwindowwithaclosebutton:
Andnowbyclickingthebutton,thewindowclosesautomatically.
3.2TheStaticTextwidget(label)
TocreatealabelonawxPythonwindow,weusetheStaticTextwidget:
Example
import wx
app= [Link]()
window= [Link](None, title= wxPython Frame (300,200)
add Panel
panel= [Link](window)
[Link]="white"
4-miniappwxPython
Wearenowgoingtocreateasmallapplicationthatshowstheuserasmallwindow.
askingtoentertheirnameanddisplayawelcomemessageafterclickingthebutton
ofvalidation.
# -*- coding: utf-8 -*-
import wx
def action(event):
s = [Link]()
[Link]("Bienvenue : " + s)
app= [Link]()
frame= [Link](None, title='Window with button')
[Link](0,0,550,300)
Create a Panel
panel = [Link](frame)
[Link]()
[Link]()
Whatisdisplayedafterexecutingthecode:
1 - About PyQt5
PyQtestisalibraryconsideredasabridgebetweenthePythonlanguageandtheGUItoolkit.
Qttoolkit,whichcanbequicklyinstalledwiththepiputilityimplementedasamodule
[Link]
underconditionssimilartopreviousQtversionsandthismeansavarietyofdelicacies,including
theGNUGeneralPublicLicense(GPL)andthecommerciallicense,butnottheGNULesserGeneralPublicLicense
PublicLicense(LGPL).PyQtsupportsMicrosoftWindowsaswellasvariousversionsofUNIX.
includingLinuxandMacOS(orDarwin).PyQtimplementsaround440classesandmorethan6,000
functionsandmethods.
2-InstallationofPyQt5andfirstprogram
2.1-InstallationofPyQt5
ThePyQt5librarycanbeeasilyinstalledviathepiputility:
pip3 install pyqt5
AfterinstallingthePyQt5library,weneedtoinstalltheauxiliarytoolsusing
thecommandprompt:
pip3 install pyqt5-tools
2.2-FirstPyQt5graphicalwindow
TocreateagraphicalwindowinPyQt5,wemust:
1. Importthesystemmodule:sys
2. Importtheclassthatgeneratestheapplication:QApplicationsfromthepackage
[Link]
3. [Link]
4. Createanapplicationusingtheinstance()methodoftheclass
QApplication
5. CreateawindowusingtheQWidget()method:fen=QWidget()
6. Visualizethewindowusingtheshow()method:[Link]()
7. Runtheapplicationusingtheexec_()method:app.exec_()
FirstgraphicalwindowcodewithPyQt5:
#-*- coding: utf-8 -*-
Necessary imports for the creation of a graphical interface
import sys
from [Link] import QApplication, QWidget
Whatdisplaysanicewindowatruntime: