0% found this document useful (0 votes)
5 views25 pages

Tkinter GUI Development in Python

The document provides an overview of creating graphical user interfaces (GUIs) in Python using Tkinter, detailing its widgets and functionalities. It also introduces the Pillow library for image processing within Tkinter applications and explains how to create a ComboBox and utilize the FileDialog module for file operations. Additionally, it outlines the structure and code for a simple text editor project using Tkinter.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

Tkinter GUI Development in Python

The document provides an overview of creating graphical user interfaces (GUIs) in Python using Tkinter, detailing its widgets and functionalities. It also introduces the Pillow library for image processing within Tkinter applications and explains how to create a ComboBox and utilize the FileDialog module for file operations. Additionally, it outlines the structure and code for a simple text editor project using Tkinter.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Graphical interface in Python with Tkinter

1 - Graphical interfaces 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 *

Creation of a tkinter window by instantiating the


class Tk
maFenetre= Tk()

your widgets here: command button, input field, labels...

Enter the main event loop


[Link]()

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.

Python and the Pillow image processing library


1-PillowandimagemanipulationonaTkinterwindow

1.1 - The Pillow library

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

Creation of the image object


load= [Link]("chemin_vers_le_fichier_images")

Creation of the photo from the image object


photo= [Link](load)

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")

Creation of the image object


load= [Link]("images/[Link]")
Creation of the photo from the image object
photo= [Link](load)

Place the image in a label


label_image= Label(root,image=photo)
label_image.place(x=0, y=0)
[Link]()

Whatisdisplayedafterexecution:

Resizing the image


ThePillowlibraryalsoallowsresizingtheimageusingthethumbnail()method.

specifyingthedimensionsinpixelsinparentheses:
# -*- coding: utf-8 -*-
Creation of the image object
load= [Link]("images/[Link]")

Resize the image


[Link]((50,50))

Tkinter ComboBox List


[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')

labelChoix= [Link](root, text= Please make a choice!


[Link]()

# 2) - create the Python list containing the elements of the Combobox list
listeProduits=["Laptop", ["Printer","Tablet","Smartphone"]

3) - Creation of the Combobox using the method [Link]()


comboList= [Link](root, values=productList)

4) - Choose the element that is displayed by default


[Link](0)

[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):

Get the selected item


select = [Link]()
You have selected: '

2.3Finalcodeofthecomboboxlistwithlinkedaction

# -*- coding: utf-8 -*-


1) - Importing necessary modules
import tkinter as tk
from tkinter import ttk

root= [Link]()
[Link]('300x200')

def action(event):

Get the selected element


select = [Link]()
You have selected: '

labelChoix= [Link](root, text= Please make a choice!


[Link]()

2) - create the Python list containing the elements of the Combobox list
listeProduits=["Laptop", ["Printer","Tablet","Smartphone"]

3) - Creating the Combobox using the method [Link]()


comboList = [Link](root, values=productList)

4) - Choose the item that appears by default


[Link](0)

[Link]()
[Link]("<<ComboboxSelected>>", action)

[Link]()

The Filedialog module Python Tkinter


1- The Filedialogue module and the associated methods

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 *

filename= [Link](initialdir= "/",title="Select


File
files","*.*"))
print(filename)

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)

Mini Python Project: Creation of a text editor part 1

1 - Creation of the system hierarchy

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.2- Creation of the main class of the file [Link]

from tkinter import *


import os
savedFile= {1:""}
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')
Main window generation
def generate(self):
[Link]()

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

Importation of the module [Link]


from [Link] import *

Creation of the dictionary that stores file objects


savedFile= {1:""}

Creation of an instance on the main class


root= Win("root","c")

Call the methods that create the window object with all its components
[Link]()
root.add_text()
root.add_menu()
[Link]()

4-PublisherOverview

Ifyouhavecodedyoursystemwellandeverythingisgoingwell,hereisanoverviewofyourlittletexteditor:

wxPython graphical interface

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

Creation of an application object using the App() method.


app= [Link]()

Creation of a frame without parent.


frame= [Link](None)

Visualize the frame.


[Link]()
[Link]()

Whatdisplaysafterexecution:

2.3Propertiesofaframewindow

AwindowfromthewxPythonlibraryisequippedwithmanyproperties:title,SetSize,

BackgroundColour…

Example.Windowofdimension400×200withagreenbackground
Importing the wxPython library.
import wx

Creation of an application object using the App() method.


app= [Link]()

Creation of a frame without a parent.


frame = [Link](None)

Window properties
[Link]= Hello World!
[Link]= green
[Link](0,0,400,200)

View the frame.


[Link]()
[Link]()

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)

Add a button to the panel


button= [Link](panel,label="un simple bouton")

[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)

Add a button to the panel


button= [Link](panel,label="un simple bouton")
[Link](50,50,200,30)

Associate the close event with the button


[Link](wx.EVT_BUTTON, action)

[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"

Create Label on panel


label= [Link](panel, label= Hello World (100,50))
[Link](True)
[Link]()

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)

# === Label nom & sortie ===


lblNom= [Link](panel)
[Link](50,50,100,10)
[Link]("Saisir votre nom")
lblResult= [Link](panel)
[Link]("")
[Link](200, 100, 100, 20)

# === TextEntry ===


edit= [Link](panel)
[Link](200,50,200,30)

=== Add a button to the panel ===


button= [Link](panel,label="Valider")
[Link](200,150,200,30)

=== Associate the close event with the button ===


[Link](wx.EVT_BUTTON, action)

[Link]()
[Link]()

Whatisdisplayedafterexecutingthecode:

The PyQt5 graphic library

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

Creating a Qt application with QApplication


app= [Link]()

we check if there is already an instance of QApplication


if not app
otherwise we create an instance of QApplication
app = QApplication([Link])

We create a window using the QWidget object


fen= QWidget()

we give a title to the window


[Link]("My first window")

We set the size of the window


[Link](500,250)

we visualize the window


[Link]()

Execution of the application, execution allows managing events.


app.exec_()

Whatdisplaysanicewindowatruntime:

You might also like