0% found this document useful (0 votes)
6 views224 pages

Python4 GUI6

The document outlines the curriculum for a course on GUI programming in Python for Semester 1, 2025/2026, covering libraries such as Tkinter and PyQT. It details various widgets, layout management, and event handling, providing examples of how to create and manipulate GUI components like buttons, labels, and entry fields. Additionally, it explains the use of Tkinter variables to manage widget values and includes code snippets for practical implementation.

Uploaded by

tandamme123
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)
6 views224 pages

Python4 GUI6

The document outlines the curriculum for a course on GUI programming in Python for Semester 1, 2025/2026, covering libraries such as Tkinter and PyQT. It details various widgets, layout management, and event handling, providing examples of how to create and manipulate GUI components like buttons, labels, and entry fields. Additionally, it explains the use of Tkinter variables to manage widget values and includes code snippets for practical implementation.

Uploaded by

tandamme123
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

FACULTY OF INFORMATION TECHNOLOGY

Semester 1, 2025/2026
 Introduction to GUI in Python

 GUI with Tkinter


◦ Basic components

◦ Advanced components

◦ Layout, Event handling

 GUI with PyQT


◦ Basic components

◦ Advanced components

◦ Layout, Event handling


Py – NLU 2
 Widgets
◦ All graphical elements in an application window are widgets
◦ All widgets are part of a window hierarchy.
◦ Most are considered 'user controls’: button, checkbutton, radiobutton,
listbox, label, entry, text, scale, scrollbar, frame, menu, menubutton

 Layout (or geometry) management


◦ Determines where to place widgets in a window or frame

 Event handling
◦ Respond to user actions (button click, keystrokes) associated with a widget
◦ Define a callback function to handle the event

Py – NLU 3
 Tkinter is a Python interface to the Tk graphics library.

◦ Tk is a graphics library widely used and available everywhere

 Tkinter is included with Python as a library. To use it:

◦ import tkinter as tk

◦ from tk import *

Py – NLU 4
 Tkinter gives you the ability to create Windows with widgets in
them

 Definition: widget is a graphical component on the screen


(button, text label, drop-down menu, scroll bar, picture,
etc…)

 GUIs are built by arranging and combining different widgets


on the screen.

Py – NLU 5
 Tkinter → tkinter  tkSimpleDialog → [Link]

 tkMessageBox → [Link]  tkFont → [Link]

 tkColorChooser →  Tkdnd → [Link]


[Link]  ScrolledText → [Link]
 tkFileDialog → [Link]  Tix → [Link]
 tkCommonDialog →  ttk → [Link]
[Link]

Py – NLU 6
Widget subclasses: Frame

Widget Label
Entry
Text

Button
Checkbutton

Radiobutton
Menu

Canvas
Scale

Listbox
Key Scrollbar
Subclass name
Class name Menubutton

Py – NLU 7
Frames are containers for other widgets
that organize and simplify layout

Labels show static text (or images), usually to identify another element
or display results
Py – NLU 8
Buttons are 'controls' that
allow users to perform
some action, for example,
calculate a result, save a
file, or quit the application

Entry widget
allows the user to
enter a single line
of input as text

Py – NLU 9
Radiobuttons allow
one selection among
several mutually
exclusive options

Checkbuttons allow
multiple selections among
mutually exclusive options

Py – NLU 10
Combobox allows one
selection from a list of
options

Text widget supports the input and


display of multiple lines of text

Py – NLU 11
 There are some common attributes of all the widgets:

◦ Width, height: Dimensions of the widgets

◦ Fonts: The font used for text on the widget

◦ Anchors: Controls where the text/contents are anchored inside the widget

◦ Relief styles: Determines the border style of the widget

◦ Image: add an image to the widget

◦ Cursors: The shape of the cursor when the cursor is over the widget

◦ …

Py – NLU 12
 Flow Diagram for Rendering a Basic GUI

Py – NLU 13
 A simple GUI with Hello, World! label.
from tkinter import *
class MyGUI:
def __init__(self):
root = Tk()
w = Label(root, text="Hello, world!")
[Link]()
[Link]()

MyGUI()

When MyGUI() is called, the init method for the class is executed to create the object
Py – NLU 14
Create the parent window. All applications have a “root” window.
This is the parent of all other widgets, create only one!

root = Tk() A Label is a widget that holds text


This one has a parent of “root” That is the
mandatory first argument to the Label’s
constructor
w = Label(root, text="Hello, world!")
Tell the label to place itself into the root window and display.
Without calling pack the Label will NOT be displayed!!!

[Link]()
Windows go into an “event loop” where they wait for things to happen
(buttons pushed, text entered, mouse clicks, etc…) or Windowing
operations to be needed (redraw, etc..). The root window to enter its
[Link]() event loop or the window won’t be displayed!

Py – NLU 15
[Link]("Simple GUI")
 title() [Link]("200x100")

◦ Sets title of root window based on a given string

 geometry()

◦ Sets size of the root window

◦ Takes string (not integers) for window’s width and height,


separated by the "x" character

Py – NLU 16
[Link]()

 Root window's event loop entered

 Window stays open, waiting to handle events

Py – NLU 17
 General form for all widgets:

◦ Create the widget

 widget = <widgetname>(parent, attributes…)

◦ [Link]()

 pack the widget to make it show up

Py – NLU 18
 This widget is used to display the text or images.

w = Label(parent, option, . . . . . )

 Where,

◦ parent – is the parent widget.

◦ option – anchor,bg, bitmap, bd, cursor, font, fg, height, image, justify,
padx, pady, text, textvariable, underline, width, wraplength, etc. . .

Py – NLU 19
Uneditable text or icons (or both)
Often used to label other widgets
Unlike most other widgets, labels aren’t interactive

 Example:
from tkinter import *
top = Tk()
lbl = Label(top, text="Hello, FIT-NLU!", relief=RAISED)
[Link]()
[Link]()
Py – NLU 20
 This widget is used to add buttons in a Python application

w = Button (parent, option = value, . . . )

 Where,

◦ parent – is the parent widget.

◦ option – active background, active foreground, command, font, height,


highlight color, text, image, justify, padx, pady, relief, width, etc. . . .

Py – NLU 21
from tkinter import *

root = Tk() # Create the root (base) window where all widgets go
w = Label(root, text="Hello, world!") # Create a label with words
[Link]() # Put the label into the window
myButton = Button(root, text="Exit")
[Link]()
[Link]() # Start the event loop

But nothing happens when we push the button! Lets fix that with an event!
Py – NLU 22
from tkinter import *

root = None
def buttonPushed():
global root
[Link]() # Kill the root window!

def main():
global root
root = Tk() # Create the root (base) window where all widgets go
w = Label(root, text="Hello, world!") # Create a label with words
[Link]() # Put the label into the window
myButton = Button(root, text="Exit",command=buttonPushed)
[Link]()
[Link]() # Start the event loop
main() Click the button will close the window
Py – NLU 23
 The Entry widget is used to accept single-line text strings

 Syntax: w = Entry( parent, option, ... )

◦ parent − This represents the parent window.

◦ options − alist of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Py – NLU 24
 Example:
class EntryGUI:
def __init__(self):
top = Tk()
[Link]("Entry GUI")
[Link]("150x100")
l1 = Label(top, text="User Name")
[Link](side=LEFT)
e1 = Entry(top, bd=5)
[Link](side=RIGHT)

[Link]()

Py – NLU 25
 Example:

class PasswordGUI:
def __init__(self):
win = Tk()
[Link]("200x150")
[Link]("Password GUI")
Label(win,text="Enter the Password", font=('Helvetica',12)).pack(pady=20)
password= Entry(win,show="*",width=20)
[Link]()
Button(win, text="Quit", font=('Helvetica bold', 10)).pack(pady=20)

[Link]()

Py – NLU 26
 Text widgets are used for entering multiple lines of text.

 Operators:

◦ Retrieve text with .get()

◦ Delete text with .delete()


class TextGUI:
◦ Insert text with .insert() def __init__(self):
window = [Link]()
[Link]('Tex Widget')
text_box = [Link]()
text_box.pack()

[Link]()
Py – NLU 27
 A checkbutton widget is like

a regular button that also holds a binary value of some kind (i.e., a
toggle).

 Syntax: w = checkbutton(parent, options)

◦ text: the label displayed next to the checkbutton

◦ variable: the control variable that tracks the current state of the checkbutton

◦ onvalue/offvalue: a checkbutton's associated control variable will be set to 1


when it is set (on), otherwise 0 will be set.

Py – NLU 28
 Example:

class CheckboxGUI:
def __init__(self):
top = [Link]()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
[Link](top, text="Machine Learning", variable=CheckVar1,
onvalue=1, offvalue=0).grid(row=0, sticky=W)
[Link](top, text="Deep Learning", variable=CheckVar2,
onvalue=0, offvalue=1).grid(row=1, sticky=W)
[Link]()

Py – NLU 29
 A combobox widget combines an

entry with a list of choices

 Syntax:

◦ current_var = [Link]()

◦ combobox = [Link](parent, textvariable=current_var)

 Adding combobox drop down list

◦ combobox['values’] = ('value1', 'value2', 'value3')

Py – NLU 30
 Example: class ComboboxGUI:
def __init__(self):
top = [Link]()
[Link]('300x200')
[Link]('Combobox Widget')
# create a combobox
selected_month = StringVar()
month_cb = Combobox(top, textvariable=selected_month)
# get first 3 letters of every month name
month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)]
# prevent typing a value
month_cb['state'] = 'readonly’
# place the widget
month_cb.pack(fill=X, padx=5, pady=5)
[Link]() Py – NLU 31
 Allows the user to choose (exactly) one of a predefined set of
options

 Syntax: w = Radiobutton ( parent, option, ... )

◦ text: The label displayed next to the radiobutton

◦ variable: The control variable that this radiobutton shares with the
other radiobuttons in the group,

◦ value: The value of radio button (if selected)

Py – NLU 32
 Example:
class RadiobuttonGUI:
def __init__(self):
top = [Link]()
[Link]('200x150')
[Link]('Radiobutton Widget')
v = IntVar()
languages = [("Python", 101), ("Perl", 102),
("Java", 103), ("C++", 104),
("C", 105)]
for language, val in languages:
Radiobutton(top,text=language,
padx=20,variable=v,
value=val).pack(anchor=W)
[Link]()

Py – NLU 33
 The Listbox widget is used to display a list of items from
which a user can select a number of items

w = Listbox(parent, option, . . . )

 Where,

◦ top – is the parent widget.

◦ option – has many attributes to set the properties like bg, bd, cursor,
font, fg, height, selectmode, etc. . . .

Py – NLU 34
 Methods:
◦ curselection(): Returns a tuple containing the line numbers of the selected
element or elements, counting from 0. If nothing is selected, returns an empty
tuple.

◦ get(first, last=None): Returns a tuple containing the text of the lines with indices
from first to last, inclusive. If the second argument is omitted, returns the text of
the line closest to first.

◦ insert(index, *elements): Insert one or more new lines into the listbox before the
line specified by index. Use END as the first argument if you want to add new
lines to the end of the listbox.

◦ nearest( y): Return the index of the visible line closest to the y coordinate y
relative to the listbox widget.
Py – NLU 35
from tkinter import *
 Example:
top = Tk()

Lbl1 = Listbox(top)
[Link](1, "Python")
[Link](2, "Perl")
[Link](3, "C")
[Link](4, "PHP")
[Link](5, "JSP")
[Link](6, "Ruby")

[Link]()
[Link]()
Py – NLU 36
 Tkinter supports some variables which are used to manipulate the values
of Tkinter widgets

 The widget will automatically get updated with the new value whenever
the value of the StringVar() variable changes.

 Methods: set() and get() are used to set and retrieve the values of these
variables.

 The values of these variables can be set using set() method or by using
constructor of these variables.

 There are 4 tkinter variables: BooleanVar(); StringVar(); IntVar();


DoubleVar()
Py – NLU 37
 Using variable’s constructor:

var = Tkinter_variable(master, value = any_value)

intvar = IntVar(master, value = 25, name ="2")


strvar = StringVar(master, "Hello, World!")
boolvar = BooleanVar(master, True)
doublevar = DoubleVar(master, 10.25)

Py – NLU 38
 Using set() method: var = Tkinter_variable(master=None)
[Link](value)
intvar = IntVar()
strvar = StringVar()
boolvar = BooleanVar()
doublevar = DoubleVar()

[Link](100)
[Link]("Hello, World!")
[Link](False)
[Link](10.36)

Py – NLU 39
var = Tkinter_variable(master = None, name = "NAME")
 Using setvar() method: [Link](name="NAME", value = any_value)

# Declaration of Tkinter variables


intvar = IntVar()
strvar = StringVar()
boolvar = BooleanVar()
doublevar = DoubleVar()

# Initialization of Tkinter variables using set() method


[Link](100)
[Link](“FIT")
[Link](False)
[Link](10.36)
Py – NLU 40
 Using get() method tkinter_variable.get()
intvar = IntVar(master, name="int")
strvar = StringVar(master, name="str")
boolvar = BooleanVar(master, name="bool")
doublevar = DoubleVar(master, name="float")

[Link](name="int", value=100)
[Link](name="str", value=“FIT")
[Link](name="bool", value=False)
[Link](name="float", value=1.236)

print("Value of IntVar()", [Link]())


print("Value of StringVar()", [Link]())
print("Value of BooleanVar()", [Link]())
print("Value of DoubleVar()",
Py – NLU [Link]()) 41
var = Tkinter_variable(master, name = "NAME")
 Using getvar() method
[Link](name = "NAME")
intvar = IntVar(master, name="int")
strvar = StringVar(master, name="str")
boolvar = BooleanVar(master, name="bool")
doublevar = DoubleVar(master, name="float")

[Link](name="int", value=100)
[Link](name="str", value="GFG")
[Link](name="bool", value=False)
[Link](name="float", value=1.236)

print("Value of IntVar()", [Link](name="int"))


print("Value of StringVar()", [Link](name="str"))
print("Value of BooleanVar()", [Link](name="bool"))
print("Value of DoubleVar()", [Link](name="float"))
Py – NLU 42
 trace() method is used on the StringVar() object to trace the
StringVar() variable, takes 2 parameters:

◦ callback: method to call when there is an operation on the object.

◦ mode: The type of operation on the StringVar() object.

 'w' (write): invoke callback when value is changed

 'r' (read): invoke callback when value is read

 'u' (unset): invoke callback when value is deleted

Py – NLU 43
class GreetingApp([Link]):
def __init__(self):
super().__init__()
[Link]('Greeting Application')
[Link]("300x300")
self.name_var = [Link]()
self.name_var.trace('w', self.create_greeting_message)
self.create_widgets()
def create_widgets(self):
def create_greeting_message(self, *args):
self.description_label = [Link](self, text=“Your name:")
name_entered = self.name_var.get()
self.description_label.grid(column=0, row=0)
greeting_message = ""
[Link] = [Link](self, textvariable=self.name_var)
if name_entered != "":
[Link](column=1, row=0)
greeting_message = "Hello " + name_entered
[Link]()
self.greeting_label = [Link](self)
self.greeting_label['text'] = greeting_message
self.greeting_label.grid(column=0, row=1, columnspan=2)
app = GreetingApp()
Py – NLU [Link]() 44
45
 This widget is very important for the process of grouping and
organizing other widgets. It is like a container

w = Frame(parent, option, . . . . . )

 Where,
◦ parent – is the parent widget.

◦ option – has many attributes to set the properties like bg, bd, cursor,
height, highlight background, highlight color, highlight thickness,
relief, width, ...

Py – NLU 46
Example:
class FrameGUI:

def __init__(self):
root = Tk()
[Link]("150x100")
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link](side=BOTTOM)
redbutton = Button(frame, text="Red", fg="red")
[Link](side=LEFT)
brownbutton = Button(frame, text="Brown", fg="brown")
[Link](side=LEFT)
bluebutton = Button(frame, text="Blue", fg="blue")
[Link](side=LEFT)
blackbutton = Button(bottomframe, text="Black", fg="black")
[Link](side=BOTTOM)

[Link]() Py – NLU 47
 Canvas is used to draw shapes in your GUI and supports
various drawing methods

 Syntax: canvas_widget = [Link](widget, option=placeholder)

◦ widget: the parent window/frame

◦ options: the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.

Py – NLU 48
 Example:

class CanvasGUI:
def __init__(self):
top = Tk()
c = Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = c.create_arc(coord, start=0, extent=150, fill="red")
line = c.create_line(10,10,200,200,fill='white')
[Link]()
[Link]()

Py – NLU 49
 A menubutton is the part of a drop-down menu that stays on the
screen all the time.
◦ Every menubutton is associated with a Menu widget that can display the
choices for that menubutton when the user clicks on it

w = Menubutton(top, option, . . . . . )
 Where,
◦ top – is the parent widget.

◦ option – has many attributes to set the properties like bg, anchorbd, bitmap,
cursor, direction, fg, height, image, justifymenu, padx, pady, text,
textvariable, etc.

Py – NLU 50
 Example:
from tkinter import *

top = Tk()
mb = Menubutton(top, text="condiments", relief=RAISED)
[Link]()
[Link] = Menu(mb, tearoff=0)
mb["menu"] = [Link]
mayoVar = IntVar()
ketchVar = IntVar()
[Link].add_checkbutton(label="mayo", variable=mayoVar)
[Link].add_checkbutton(label="ketchup", variable=ketchVar)
[Link]()
[Link]() Py – NLU 51
 The goal of this widget is to allow us to create all kinds of
menus that can be used by our applications. Three menu
types:

◦ pop-up, w = Menu (top, option, . . . )

 Where,
◦ toplevel,
◦ top – is the parent widget.
◦ pull-down.
◦ option – has many attributes to set the properties like bg,
anchorbd, bitmap, cursor, direction, fg, height, image,
justifymenu, padx, pady, text, textvariable, etc

Py – NLU 52
Py – NLU 53
54
[Link]

 An improved look and feel of Tk widgets


 Styled widgets: Button, Checkbutton, Entry, Frame, Label,
LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale,
Scrollbar, Spinbox, Combobox, Notebook, Progressbar,
Separator, Sizegrip, Treeview.
from tkinter import * l1 = [Link](text="Test", fg="black", bg="white")
from tkinter import ttk l2 = [Link](text="Test", fg="black", bg="white")

style = [Link]()
[Link]("[Link]", foreground="black", background="white")

l1 = [Link](text="Test", style="[Link]")
l2 = [Link](text="Test", style="[Link]")
Py – NLU 55
 Tkinter Treeview: a UI widget that presents data in hierarchical
form, although non-hierarchical data is also supported.

◦ can be used as a table widget too

 Tkinter Treeview gives an improved look to the data columns.

 Tkinter Treeview is derived from [Link] module


(introduced in Tk 8.5 ).

Py – NLU 56
 Some definitions:

◦ Item: One of the entities being displayed in the widget. Each item is
associated with a textual label, and may also be associated with an image.

◦ iid: Every item in the tree has a unique identifier string called the iid, given
by users or generated by ttk.

◦ Child: The items directly below a given item in a hierarchy.

◦ Parent: For a given item, if it is at the top of the hierarchy it is said to have
no parent; if it is not at the top level, the parent is the item that contains
it.

Py – NLU 57
 Some definitions:

◦ Ancestor: The ancestors of an item include its parent, its parent's parent, and so
on up to the top level of the tree.

◦ Visible: Top-level items are always visible. Otherwise, an item is visible only if all
its ancestors are expanded.

◦ Descendant: The descendants of an item include its children, its childrens'


children, and so on.

◦ Tag: can associate one or more tag strings with each item. use these tags to
control the appearance of an item.

Py – NLU 58
 Example:

class TreeviewGUI:
def __init__(self):
root = [Link]()
[Link]("Treeview in Tk")
treeview = [Link]()
item = [Link]("", [Link], text="Item 1")
subitem = [Link](item, [Link], text="Subitem 1")
[Link](subitem, [Link], text="Another item")
[Link]()
[Link]()

Py – NLU 59
 Example:
class TreeViewGUI:
def __init__(self):
data = [("John Doe", 28, "Engineer"), ("Jane Smith", 34, "Designer"),
("Sam Brown", 22, "Data Analyst"), ("Lisa White", 29, "Manager")]
root = [Link]()
[Link]("Simple Table GUI")
tree = [Link](root, columns=("Name", "Age", "Occupation"), show="headings")
[Link]("Name", text="Name")
[Link]("Age", text="Age")
[Link]("Occupation", text="Occupation")
for row in data:
[Link]("", [Link], values=row)
scrollbar = [Link](root, orient="vertical", command=[Link])
[Link](yscroll=[Link])
[Link](side=[Link], fill=[Link], expand=True)
[Link](side=[Link], fill=tk.Y)
[Link]() Py – NLU 60
 Selection method returns the tuple of selected items.

 Selection method returns the row index of selected items in


Treeview.
◦ can return more than one indexes at a time in a tuple format.

 The value of selection can be stored in a variable and then using


if-else it can be put to condition.

 Items of a selected row can be accessed or altered by providing the


index number.
◦ Example: row[3], row[1], row[2]

Py – NLU 61
 Example:
def show_selected(self):
class TreeviewGUI:
selected_iid = [Link]()
def __init__(self):
print([Link](selected_iid[0], "text"))
root = [Link]()
[Link]("Treeview in Tk")
[Link] = [Link]()
item = [Link]("", [Link], text="Item 1") Item 1
subitem = [Link](item, [Link], text="Subitem 1") Subitem 1
Another item
[Link](subitem, [Link], text="Another item")
[Link]()
[Link](root, text="Show Selected", command=self.show_selected).pack()
[Link]()

Py – NLU 62
 Example:

class TreeviewGUI:
def __init__(self): def show_selected(self):
root = [Link]() print([Link]())
[Link]("Treeview in Tk")
[Link] = [Link]()
item = [Link]("", [Link], text="Item 1")
subitem = [Link](item, [Link], text="Subitem 1") ('I001',)
[Link](subitem, [Link], text="Another item") ('I003',)
[Link]()
[Link](root, text="Show Selected", command=self.show_selected).pack()
[Link]()

Py – NLU 63
 The Scrollbar widget provides a slide controller for Listbox,
Text, Canvas, and Entry widgets.

 Syntax: w = Scrollbar ( parent, option, ... )

◦ parent − This represents the parent window.

◦ options − the list of most commonly used options for this widget, can
be used as key-value pairs separated by commas.

 orient: HORIZONTAL for a horizontal scrollbar, orient=VERTICAL for a


vertical one.

Py – NLU 64
 Methods:

◦ get(): Returns two numbers (a, b) describing the current position of the
slider.

 The a value: the position of the left or top edge of the slider, for
horizontal and vertical scrollbars respectively;

 The b value: the position of the right or bottom edge.

◦ set (first, last ): To connect a scrollbar to another widget w

Py – NLU 65
 Example:
class ScrollbarGUI:
def __init__(self):
root = Tk()
scrollbar = Scrollbar(root)
[Link](side=RIGHT, fill=Y)

mylist = Listbox(root, yscrollcommand=[Link])


for line in range(100):
[Link](END, "This is line number " + str(line))

[Link](side=LEFT, fill=BOTH)
[Link](command=[Link])
mainloop() Py – NLU 66
 A progress bar widget provides feedback to users about the
progress of a lengthy operation.

 Syntax: [Link](container, orient, length, mode)


◦ container: the parent component of the progressbar.

◦ orient: can be either 'horizontal' or 'vertical’.

◦ length: represents the width of a horizontal progress bar or the height


of a vertical progressbar.

◦ mode: can be either 'determinate' or 'indeterminate'

Py – NLU 67
class ProgressbarGUI:
 Example: def increment(self):
for i in range(100):
self.p1["value"] = i + 1
[Link]()
[Link](0.1)
def __init__(self):
[Link] = [Link]()
[Link]('320x240')
self.p1 = [Link]([Link], length=200, cursor='spider',
mode="determinate",
orient=[Link])
[Link](row=1, column=1)
btn = [Link]([Link], text="Start", command=[Link])
[Link](row=1, column=0)
[Link]()

Py – NLU 68
 Scale widget: allows to select a specific value from a range of values in a
sliding bar.

 Syntax: w = Scale(parent, options)

◦ parent – root window.

◦ options: bg, fg, bd – border, orient (vertical or horizontal), from, to, troughcolor,
state, sliderlength, label, highlightbackground, cursor, circle, dot, etc.

 Methods:

◦ get(): This method returns the current value of the scale.

◦ set (value ): Sets the scale's value.

Py – NLU 69
 Example:
class ScaleGUI:
def __init__(self):
top = Tk()
[Link]("150x100")
self.v = DoubleVar()
scale = Scale(top, variable=self.v, from_=1, to=50, orient=HORIZONTAL)
[Link](anchor=CENTER)
btn = Button(top, text="Value", command=[Link])
[Link](anchor=CENTER)
[Link] = Label(top)
[Link]()
[Link]()
def select(self):
sel = "Value = " + str([Link]())
[Link](text=sel) Py – NLU 70
71
 Problem: Different widgets have different sizes and you want
them placed in an organized and visually appealing way in the
window

◦ All widgets have a 'natural' (or default) size, and the layout manager
uses a complex algorithm to determine how to make everything fit
within the window constraints

Py – NLU 72
 Tkinter has 3 layout managers

◦ Pack: easy, but limited. Allows you to specify location and padding
relative to other widgets within a container.

◦ Place: explicitly set the position and size of a window in either


absolute or relative terms. Have complete control, but more
complex.

◦ Grid: places widgets in a 2-dimensional table. A widget's position is


defined by row and column.

Py – NLU 73
 The pack layout manager tries to place each widget “next to” the
previous widget in a container (more complex than the grid layout).

 Options:
◦ side: TOP, BOTTOM, LEFT, RIGHT

◦ expand: True if the widget stretchs to fill the available space

◦ fill: determines if a widget will occupy the available space (X, Y, or BOTH)

◦ ipadx, ipady: Internal paddings

◦ padx, pady: External paddings

◦ anchor: anchor the widget to the edge of the allocated space

Py – NLU 74
class PackGUI:
window = [Link]()
[Link]("GUI")

top_frame = [Link](window).pack()
bottom_frame = [Link](window).pack(side="bottom")
btn1 = [Link](top_frame, text="Button1",
fg="red").pack()
btn2 = [Link](top_frame, text="Button2", fg="green").pack()
btn3 = [Link](bottom_frame, text="Button3", fg="purple").pack(
side="left")
btn4 = [Link](bottom_frame, text="Button4", fg="orange").pack(side="left")
[Link]()
PackGUI()

Py – NLU 75
 All widgets have a .grid(row=r, column=c) method that will
place a widget in the cell (r,c) of a 2-D table.

 Options:

◦ sticky: allows to move or stretch a widget to the borders of a cell

◦ columnspan, rowspan: a widget can span more than one cell in the grid

◦ ipadx, ipady: Internal paddings

◦ padx, pady: External paddings

Py – NLU 76
 Sticky option:
sticky Parameter Description
tk.W Move the widget to the left cell boundary.

tk.W + tk.N Move the widget left and up so that it is in the upper-left corner.

tk.E + tk.W Stretch the widget so that it fills the cell horizontally.

tk.E + tk.W + tk.S Stretch the widget so that it fills the cell horizontally and move it
down to the bottom cell boundary.

tk.E + tk.W + tk.N + tk.S Stretch the widget so it fills the entire cell.

Py – NLU 77
class GridGUI:
def __init__(self):
top = [Link]()
checkVar1 = IntVar()
checkVar2 = IntVar()
[Link](top, text="Machine Learning", variable=checkVar1,
onvalue=1, offvalue=0).grid(row=0, sticky=W)
[Link](top, text="Deep Learning", variable=checkVar2,
onvalue=0, offvalue=1).grid(row=1, sticky=W)
[Link]()

GridGUI()
Py – NLU 78
 All widgets have a .place(x, y, width, height) method that can
be used to specify the exact location and size of a widget.

 The placer geometry management gives you fine control over


the positioning of widgets by allowing you to:

◦ Specify coordinates (x, y).

◦ Use relative positioning based on anchor points.

Py – NLU 79
 Absolute positioning: [Link](x=50, y=50)

 Relative positioning:
[Link](relx=0.5, rely=0.5,
anchor=CENTER)

 width and height:

◦ [Link](width=120, height=60)

◦ [Link](relwidth=0.5, relheight=0.5)
Py – NLU 80
class PlaceGUI:
def __init__(self):
root = [Link]()
[Link]("Place layout Example")
[Link]("300x300+50+100")
[Link](root, text="Which cities would you like to travel to?",
wraplength=200,).place(x=50, y=20)
cities_listbox = [Link](root, selectmode=[Link], width=24)
cities_listbox.place(x=40, y=65)
cities = ["Beijing", "Singapore", "Tokyo", "Dubai", "New York"]
for city in cities:
cities_listbox.insert([Link], city)
end_button = [Link](root, text="End", command=quit)
end_button.place(x=125, y=250)
[Link]()
PlaceGUI() Py – NLU 81
 Pack Layout Manager

◦ Uses Frame widget to group other widgets

◦ Uses pack function to lay out widgets

 Grid Layout Manager

◦ Uses main_window to group widgets

◦ Widgets are laid out using row and column attributes

The grid layout manager for most interface design problems

Py – NLU 82
 Use messagebox method in the Tkinter to create alert boxes

 For generating an alert ➔ use messagebox function showinfo.

 For creating a question ➔ use the askquestion method

 The response will be:

◦ 1, if user click Yes

◦ 0, otherwise

Py – NLU 83
class ImageGUI:
def __init__(self):
window = [Link]()
[Link]("GUI")

icon = [Link](file=“[Link]")

label = [Link](window, image=icon)


[Link]()
[Link]()

ImageGUI()
Py – NLU 84
class AlertBoxGUI:
def __init__(self):
window = [Link]()
[Link]("GUI")
[Link]("Alert Message", "This is just a alert message!")
response = [Link]("Tricky Question", "Do you love Java?")

if response == 1:
[Link](window, text="Yes, offcourse I love Java!").pack()
else:
[Link](window, text="No, I don't love Java!").pack()
[Link]()

AlertBoxGUI()
Py – NLU 85
 Group and organize your widgets in a coherent design.

 Tkinter has four basic ways to group widgets:

◦ Frame: create a container for a set of widgets to be displayed as a unit.

◦ LabelFrame: group a number of related widgets using a border and a title.

◦ PanedWindow: Group one or more widgets into “panes”, where the “panes”
can be re-sized by the user by dragging separator lines.

◦ Notebook: A tabbed set of frames, only one of which is visible at any given
time.

Py – NLU 86
 The Frame and LabelFrame
groups, the frame is the “parent”
of the widgets displayed inside
the frame.

 The PanedWindow and Notebook


groups, use an .add(widget)
function to add your widgets to
the group
Py – NLU 87
 Tkinter provide a library like messagebox.

◦ show several Information, Error, Warning, Cancellation ETC in the form of


Message-Box.

 Different message boxes:

◦ showinfo() – To display some important information.

◦ showwarning() – To display some type of Warning.

◦ showerror() –To display some Error Message.

◦ askquestion() – To display a dialog box that asks with two options YES or NO.

Py – NLU 88
 Tkinter provide a library like messagebox.

◦ show several Information, Error, Warning, Cancellation ETC in the form of


Message-Box.

 Different message boxes:

◦ askokcancel() – To display a dialog box that asks for two options OK or CANCEL.

◦ askretrycancel() – To display a dialog box that asks for two options RETRY or
CANCEL.

◦ askyesnocancel() – To display a dialog box that asks with three options YES or NO
or CANCEL.

Py – NLU 89
 Dialog boxes are a type of window used in applications to get
information from users, inform them that some event has
occurred, confirm an action and more.
 Syntax: messagebox.name_of_function(Title, Message, [,
options])
◦ name_of_function – Function name that which we want to use.
◦ Title – Message Box’s Title.
◦ Message – Message that you want to show in the dialog.
◦ Options –To configure the options.

Py – NLU 90
 Example:

class MessageboxGUI:
def submit(self):
[Link]("Form",
"Do you want to Submit")
def __init__(self):
main = Tk()
[Link]("100x100")
B1 = Button(main, text="Submit", command=[Link]())
[Link]()
[Link]()

Py – NLU 91
92
 Tkinter handles events by allowing callback functions to be
associated with any event for any widget.

 Tkinter can handle the following event types:

◦ Keyboard events: KeyPress, KeyRelease

◦ Mouse events: ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel

◦ Window events: Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,


Colourmap, Gravity, Reparent, Property, Destroy, Activate, Deactivate

Py – NLU 93
Attrib. Explanations
serial serial number of the event
num number of the mouse button pressed (ButtonPress,
ButtonRelease) (1=LEFT, 2=CENTER, 3=RIGHT, etc.)
focus boolean which indicates whether the window has the focus
(Enter, Leave)
height height of the exposed window (Configure, Expose)
width width of the exposed window (Configure, Expose)
keycode keycode of the pressed key (KeyPress, KeyRelease)

Py – NLU 94
Attrib. Explanations
state state of the event as a number (ButtonPress, ButtonRelease, Enter,
KeyPress, KeyRelease, Leave, Motion)
time time at which the event occurred. Under Microsoft Windows, this
is the value returned by the GetTickCount( ) API function.
x x-position of the mouse relative to the widget
y y-position of the mouse relative to the widget
x_root x-position of the mouse on the screen relative to the root
(ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
y_root y-position of the mouse on the screen relative to the root
(ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)

Py – NLU 95
Attrib. Explanations
char pressed character (as a char)(KeyPress, KeyRelease)
send_event
keysym keysym of the the event as a string (KeyPress, KeyRelease)
keysym_num keysym of the event as a number (KeyPress, KeyRelease)
type type of the event as a number
widget widget for which the event occurred
delta delta of wheel movement (MouseWheel)

Py – NLU 96
 All event handling requires a string description of the event to be
bound.

 The general format is as follows: <Modifier- Type - Qualifier>


◦ Type: the kind of event that we wish to bind: user actions like Button, and
Key, or window manager events like Enter, Configure, and others.

◦ Modifier: Optional prefix that modifies the main event: Control, Shift, Alt,
Double

◦ Qualifier: Optional suffix that identifies which button or key to respond to,
like 1 for the left mouse button or Return for the Enter key

Py – NLU 97
 KeyPress: Activated when a keyboard button has been pressed, the

 Key: event can also be used for this.

 KeyRelease: Activated when a keyboard button is released.

 Button: Activated when a mouse button has been clicked.

 ButtonRelease: Activated when a mouse button has been released.

 Motion: Activated when the mouse cursor moves across the designated
widget.

 Enter: Activated when the mouse cursor enters the designated widget.

Py – NLU 98
 Leave: Activated when the mouse cursor leaves the designated
widget.

 MouseWheel: Activated when the mouse wheel is scrolled.

 FocusIn: Activated when the designated widget gains focus through


user input such as the mouse clicking on it.

 FocusOut: Activated when the designated widget loses focus.

 Configure: Activated when the designated widget's configurations


have changes such as its width being adjusted by the user or its
border being adjusted.

Py – NLU 99
 The modifier names that you can use in event sequences
include:
Alt True when the user is holding the alt key down.

This modifier generalizes an event type. For example, the event pattern '<Any-
Any
KeyPress>' applies to the pressing of any key.

Control True when the user is holding the control key down.

Specifies two events happening close together in time. Ex. <Double-Button-


Double
1> describes two presses of button 1 in rapid succession.

Lock True when the user has pressed shift lock.

Shift True when the user is holding down the shift key.

Triple Like Double, but specifies three events in rapid succession.

Py – NLU 100
 Events that occur as a result of user interaction with a mouse

 Tkinter events described by strings following pattern


<modifier-type-detail>

◦ type specifies kind of event (e.g. Button and Return)

 Button here is mouse button!

◦ Specific mouse button is example of a detail

◦ Prefix Double is example of a modifier

Py – NLU 101
Event format Description
<ButtonPress-n> Mouse button n has been selected while the mouse
pointer is over the component. n may be 1 (left
button), 2 (middle button) or 3 (right button). (e.g.,
<ButtonPress-1>).
<Button-n>, <n> Shorthand notations for <ButtonPress-n>.
<ButtonRelease-n> Mouse button n has been released.
<Bn-Motion> Mouse is moved with button n held down.
<Prefix-Button-n> Mouse button n has been Prefix clicked over the
component.
Prefix may be Double or Triple.
<Enter> Mouse pointer has entered the component.
<Leave> Mouse pointer has exited the component.

Py – NLU 102
 Keyboard events generated when users press and release keys
Event format Description of Event
<KeyPress> Any key has been selected.
<KeyRelease> Any key has been released.
<KeyPress-key> key has been selected or released.
<KeyRelease-key>
<Key>, <Key-key> Shorthand notation for <KeyPress> and <KeyPress-key>.
<key> Shorthand notation for <KeyPress-key>. This format works
only for printable characters (excluding space and less-than
sign).
<Prefix-key> key has been selected while Prefix is held down. Possible
prefixes are Alt, Shift and Control. Note that multiple prefixes
are also possible (e.g., <Control-Alt-key>).

Py – NLU 103
 There are 3 ways to bind events to widgets in Tkinter:

◦ The bind() method, which can be called on any widget

◦ The bind_class() method, which binds events to a particular widget


class.

◦ The bind_all() method, which binds events to the whole application

Py – NLU 104
 The bind() method of Tkinter is utilized to connect an event
passed in the widget along with the event handler.
 The event handler is the function invoked when the events
occur.
 Syntax: widget_name.bind(sequence = None, func = None,
add = None)
◦ sequence: describes what event we expect
◦ func: a function to be called when that event happens to the widget
◦ add: one or multiple events binned on the widget

Py – NLU 105
Instance-level Binding
widget_name.bind(event, event_handler)
import tkinter as tk

class BindMethodGUI():
def on_click1(self, event):
print("Handler 1")

def __init__(self):
root = [Link]()
button = [Link](root, text="Click Me")
[Link]()
[Link]("<Button-1>", self.on_click1)

[Link]()
Py – NLU 106
 Bind more than one function to a particular widget

import tkinter as tk

class BindMethodGUI():

def __init__(self): def on_click1(self, event):


root = [Link]() print("Handler 1")
button = [Link](root, text="Click Me")
[Link]() def on_click2(self, event):
# Bind 2 events for event <Button-1> (left mouse click) print("Handler 2")
[Link]("<Button-1>", self.on_click1)
[Link]("<Button-1>", self.on_click2, add=True) # add=True 2 events on the button
[Link]()

Py – NLU 107
Class-level Binding
 Bind an event to all widgets of a class
w.bind_class(className, sequence=None, func=None, add=None)

import tkinter as tk
class Class_Level_BindingGUI:
def __init__(self):
root = [Link]()
entry_username = [Link]([Link])
entry_password = [Link]([Link])
entry_username.bind_class("Entry", "<Return>", [Link])
entry_username.pack()
entry_birthday.pack() def onReturn(self, event):
entry_password.pack() print("Return pressed")
[Link]()
Py – NLU 108
Application-level Binding
 A certain event calls a handler no matter what widget has the
focus or is under the mouse
w.bind_all(sequence=None, func=None, add=None)

class Application_Level_BindingGUI:
def __init__(self):
root = [Link]()
entry_username = [Link]([Link]) def onReturn(self, event):
entry_birthday = [Link]([Link]) print("Return pressed")
entry_password = [Link]([Link])
entry_username.bind_all("<Return>", [Link])
entry_username.pack()
entry_birthday.pack()
entry_password.pack()
[Link]() Py – NLU 109
 Assign a function to Button widget based on command
attribute def increase(self):
value = int(self.lbl_value["text"])
self.lbl_value["text"] = f"{value + 1}"
class CommandGUI:
def __init__(self): def decrease(self):
window = [Link]() value = int(self.lbl_value["text"])
[Link](0, minsize=50, weight=1) self.lbl_value["text"] = f"{value - 1}"
[Link]([0, 1, 2], minsize=50, weight=1)
self.btn_decrease = [Link](master=window, text="-", command=[Link])
self.btn_decrease.grid(row=0, column=0, sticky="nsew")
self.lbl_value = [Link](master=window, text="0")
self.lbl_value.grid(row=0, column=1)
self.btn_increase = [Link](master=window, text="+", command=[Link])
self.btn_increase.grid(row=0, column=2, sticky="nsew")
[Link]() Py – NLU 110
111
 MVC is a widely used software architectural pattern in GUI-
based applications

Model represents the data of the


application

View displays the data from the


Model to the user and sends user
inputs to the Controller

Controller acts as an intermediary


between the Model and the View

Py – NLU 112
 Build an application to manage todo list:

class TaskModel: class TaskView:


def __init__(self): def __init__(self, root, controller):
[Link] = [] [Link] = root
[Link] = controller
def add_task(self, task): self.task_entry = [Link](root)
[Link](task) self.task_entry.pack(pady=10)
self.add_button = [Link](root, text="Add Task",
def get_tasks(self): command=[Link].add_task)
return [Link] self.add_button.pack()
self.task_listbox = [Link](root)
self.task_listbox.pack()
def update_task_list(self, tasks):
self.task_listbox.delete(0, [Link])
for task in tasks:
self.task_listbox.insert([Link],
Py – NLU task) 113
 Build an application to manage todo list:
class TaskController:
def __init__(self, root):
[Link] = root
[Link] = TaskModel()
[Link] = TaskView(root, self)

def add_task(self):
task = [Link].task_entry.get()
if task:
[Link].add_task(task)
[Link].update_task_list([Link].get_tasks())
[Link].task_entry.delete(0, [Link])

Py – NLU 114
 Modularity − Each component (model, view, and controller) can be
modified or extended independently, promoting code modularity and
reusability.

 Maintainability − Changes to the user interface or application logic can


be made without affecting the other components, making the codebase
easier to maintain.

 Testability − The separation facilitates unit testing, as each component's


functionality can be tested in isolation.

 Scalability − The MVC pattern supports adding new features or


components without major changes to the existing codebase.

Py – NLU 115
116
 Qt is a cross platform GUI application development framework
written in C++.

◦ Qt applications can run natively on Windows, Linux, macOS, Android


and embedded systems.

 PyQt is developed and maintained by Riverbank Computing


and is available under both paid and free licensing models.

 PyQt6 is the binding for Qt6 (Python 3 supports Qt5, Qt6)


pip3 install pyqt6

Py – NLU 117
 Qt Designer which can be used to design GUIs in the simplest
drag and drop manner.

Py – NLU 118
 A comparison between Tkinter and PyQT

Py – NLU 119
import sys
from [Link] import QApplication, QWidget

class MainWindow(QWidget):
def __init__(self):
super().__init__()
# set the window title if __name__ == '__main__':
[Link]('Hello World') app = QApplication([Link])
[Link](100, 100, 320, 210) # create the main window
# show the window window = MainWindow()
[Link]() # start the event loop
[Link]([Link]())
The argv from the sys module us used to accept one or more command line arguments
Py – NLU 120
 Each PyQt application has one and only one QApplication object.
The QApplication object holds an event loop.

 An event loop manages all events of the PyQt application. It checks


the event queue continuously and forwards the events to their
handlers.

 Call the [Link]() to start the event loop.

 Use QMainWindow to create the main window for the PyQt


application and call the show() method to display the window on
the screen.

Py – NLU 121
 Every PyQt application needs one instance of QApplication
class.

 The QApplication object holds the event loop of the


application.

 The event loop is responsible for managing all events of the


application including user interactions with the GUI.

Py – NLU 122
 When a user interacts with the Qt application (by pressing a key or
pushing a button), PyQt generates an event and places it on an event
queue.
 The event loop continuously checks the event queue. If the event loop
finds an event, it’ll forward the event to a specific event handler.
 The event handler processes the event and passes the control back to
the event loop for processing the next events.

Py – NLU 123
 The event-driven programming paradigm, a program has the
following flow:

◦ Create widgets like labels, line edits, and buttons.

◦ Start an event loop that waits for events.

◦ Respond to events when they occur by executing callables.

Note that a callable is a function, a method, or an


object that implements the __call__() method.

Py – NLU 124
 A signal is a special property of an object that is emitted when
an event occurs.

 A slot is a callable that can receive a signal and respond to it


accordingly.

 PyQt uses signals and slots to wire up events with callables.

Py – NLU 125
class MainWindow(QWidget):
def __init__(self):
super().__init__()
 Example: [Link]('Qt Signals & Slots')

# create widgets
label = QLabel()
line_edit = QLineEdit()
textChanged signal to line_edit.[Link]([Link])
the setText method of
the QLabel object # place the widgets
layout = QVBoxLayout()
[Link](label)
[Link](line_edit)
[Link](layout)
# show the window
[Link]()
Py – NLU 126
127
 QLabel: create a label widget that displays text, an image, or
an animated image (GIF)
label = QLabel()
[Link]('Hello, QLabel!')
 QLabel with text:
label = QLabel()
 QLabel with image: pixmap = QPixmap('[Link]')
[Link](pixmap)
 QLabel widget to display an animated image
label = QLabel()
movie = QMovie('[Link]')
[Link](movie)
[Link]()
Py – NLU 128
 QPushButton: create a button widget, which can be a push
button or a toggle button

 QPushButton with text: button = QPushButton('Click Me')

button = QPushButton('Delete')
 QPushButton with image: [Link](QIcon('[Link]'))

button = QPushButton('Toggle Me')


[Link](True)
 Creating a toggle button: [Link](self.on_toggle)
Py – NLU 129
 QLineEdit: create a single-line text-entry widget.

 Step by step: create a new QLineEdit object that uses

◦ No arguments.

◦ With only a parent widget.

◦ Or with a default string value as the first argument.

from [Link] import QLineEdit


line_edit = QLineEdit('Default Value', self)

Py – NLU 130
Property Type Description
text string The content of the line edit
readOnly Boolean True or False. If True, the line
edit cannot be edited
clearButtonEnabled Boolean True to add a clear button
placeholderText string The text that appears when
the line edit is empty
maxLength integer Specify the maximum number
of characters that can be
entered
echoMode [Link] Change the way the text
displays e.g., password
Py – NLU 131
class MainWindow(QWidget):
def __init__(self):
super().__init__()
 Simple QLineEdit
[Link]('PyQt QLineEdit Widget')
[Link](100, 100, 320, 210)
search_box = QLineEdit(
self,
placeholderText='Enter a keyword to search...',
clearButtonEnabled=True)
# place the widget on the window
layout = QVBoxLayout()
[Link](search_box)
[Link](layout)
# show the window
[Link]()

Py – NLU 132
class MainWindow(QWidget):
 Password:
def __init__(self):
super().__init__()

[Link]('PyQt QLineEdit Widget')


[Link](100, 100, 320, 210)

password = QLineEdit(self, echoMode=[Link])


# place the widget on the window
layout = QVBoxLayout()
[Link](password)
[Link](layout)
# show the window
[Link]()
Py – NLU 133
 Auto-complete feature
common_fruits = QCompleter([
'Apple', 'Apricot',
'Banana', 'Carambola',
'Olive', 'Oranges',
'Papaya', 'Peach',
'Pineapple', 'Pomegranate',
'Rambutan', 'Ramphal',
'Raspberries', 'Rose apple',
'Starfruit', 'Strawberries',
'Water apple',
])
fruit = QLineEdit(self)
[Link](common_fruits)
Py – NLU 134
 Summary:

◦ QLineEdit is used to create a single-line entry widget.

◦ Use the echoMode property to change the way the text is displayed.

◦ Use the QLineEdit widget with a QCompleter widget to support the


auto-complete feature.

Py – NLU 135
136
 QHBoxLayout lays out widgets in a horizontal row, from left to
right

 QVBoxLayout lays out widgets in a vertical column, from top


to bottom.

Py – NLU 137
 QGridLayout lays out widgets in a two-dimensional grid.
Widgets can occupy multiple cells

 QFormLayout lays out widgets in a 2-column descriptive


label- field style

Py – NLU 138
 QHBoxLayout divides the parent widget into horizontal boxes
and places the child widgets sequentially from left to right.

 Step by step:

◦ Create a layout object from a layout class, layout = QHBoxLayout()

◦ Assign the layout object to the parent widget’s layout property using
the setLayout() method.

◦ Add widgets to the layout using the addWidget() method of the layout
object.

Py – NLU 139
 Example: class MainWindow(QWidget):
def __init__(self):
super().__init__()

[Link]('PyQt QHBoxLayout')
# create a layout
layout = QHBoxLayout()
[Link](layout)
# create buttons and add them to the layout
titles = ['Yes', 'No', 'Cancel']
buttons = [QPushButton(title) for title in titles]
for button in buttons:
[Link](button)
# show the window
[Link]() Py – NLU 140
 Alignments

◦ Align left: To align the button to the left of the parent widget ➔ add a
horizontal spacer (addStretch()) after the child widgets to the
QHBoxLayout

◦ Align right: add a spacer at the beginning of the layout to push the
buttons to the right

Py – NLU 141
 Alignments

◦ Align center: add one horizontal spacer at the beginning and the other
at the end of the layout

◦ Placing a horizontal spacer between widgets:

Py – NLU 142
 Alignments

◦ Setting layout stretch factors: to set the space that the child widget can
stretch ➔ use setStretchFactor() method of the QHBoxLayout object

◦ Setting spaces between widgets:use the setSpacing() method of the


QHBoxLayout object

Py – NLU 143
 Alignments

◦ Setting content margins:

 By default, the QHBoxLayout sets specific left, top, right, and bottom
margins for child widgets.

 To change the margins ➔ use the setContentsMargins() method to set the


left, top, right, and bottom margins

Py – NLU 144
 QVBoxLayout divides the parent widget into vertical boxes
and places the child widgets sequentially from top to bottom

 Step by step usage:

◦ Create a QVBoxLayout object: layout = QVBoxLayout()

◦ Assign the layout object to the parent widget’s layout property using
the setLayout() method.

◦ Add widgets to the layout using the addWidget() method of the layout
object.

Py – NLU 145
 Example: class MainWindow(QWidget):
def __init__(self):
super().__init__()

[Link]('PyQt QVBoxLayout')
# create a layout
layout = QVBoxLayout()
[Link](layout)
# create buttons and add them to the layout
titles = ['Find Next', 'Find All', 'Close']
buttons = [QPushButton(title) for title in titles]
for button in buttons:
[Link](button)
# show the window
[Link]() Py – NLU 146
 Alignment:

◦ QVBoxLayout stretches each widget type in a specific


way

◦ increase the height of the parent widget, the heights of


the buttons don’t change

◦ Align bottom: add a vertical spacer at the beginning of


the layout by using the addStretch() method of the
QVBoxLayout object

Py – NLU 147
 Alignment:

◦ Align top: add a vertical spacer as the last item of the


layout

◦ Align center: add a vertical spacer at the beginning and


one at the end of the layout

◦ add a vertical spacer between the widgets

in the QVBoxLayout

Py – NLU 148
 Alignment:

◦ Setting layout stretch factors: use setStretchFactor()


method sets a stretch factor for the widget to stretch
within the layout.

◦ Setting spaces between widgets: use the setSpacing()


method.

◦ Setting content margins: use the setContentsMargins()


method

Py – NLU 149
 GridLayout presents with a grid of cells arranged in rows and
columns. layout = QGridLayout()
 addWidget() method used to add a widget to a specific row
and column.
[Link](widget, row, column, rowSpan, columnSpan, alignment)
•widget is a child widget that you want to place on the grid.
•row is a row index that starts from 0.
•column is a column index that starts from 0.
•rowSpan is the number of rows that you want to span.
•columnSpan is the number of columns that you want to span.
•alignment specifies the alignment of the widget within the cell.
Py – NLU 150
 Alignment Flag:
◦ AlignAbsolute: ensures the alignment behaves without mirroring.

◦ AlignBaseline: Align the widget with the baseline.

◦ AlignBottom: Align the widget with the bottom edge.

◦ AlignCenter: Centers the widget in both dimensions.

◦ AlignHCenter: Centers the widget horizontally in the available space.

◦ AlignHorizontal_Mask: AlignLeft | AlignRight | AlignHCenter |


AlignJustify | AlignAbsolute

Py – NLU 151
 Alignment Flag:
◦ AlignJustify: Justifies the text in the available space.

◦ AlignLeft: Align the widget with the left edge.

◦ AlignRight: Align the widget with the right edge.

◦ AlignTop: Align the widget with the top edge.

◦ AlignVCenter: Centers the widget vertically in the available space.

◦ AlignVertical_Mask: AlignTop | AlignBottom | AlignVCenter |


AlignBaseline

Py – NLU 152
class MainWindow(QWidget):
def __init__(self):
super().__init__()
[Link]('Login Form')
 Example: Login form # set the grid layout
layout = QGridLayout()
[Link](layout)
# username
[Link](QLabel('Username:'), 0, 0)
# password [Link](QLineEdit(), 0, 1)
[Link](QLabel('Password:'), 1, 0)
[Link](QLineEdit(echoMode=[Link]), 1, 1)
# buttons
[Link](QPushButton('Log in'), 2, 0,
alignment=[Link])
[Link](QPushButton('Close'), 2, 1,
alignment=[Link])
# show the window
[Link]()

Py – NLU 153
 QFormLayout is a convenient way to create two column form,

◦ each row consists of an input field associated with a label (the left
column contains the label and the right column contains an input
field).

layout = QFormLayout(self)
[Link](layout) # self is the parent widget

Py – NLU 154
class MainWindow(QWidget):
def __init__(self):
super().__init__()
[Link]('Sign Up Form')
layout = QFormLayout()
[Link](layout)
[Link]('Name:', QLineEdit(self))
[Link]('Email:', QLineEdit(self))
[Link]('Password:', QLineEdit(self, echoMode=[Link]))
[Link]('Confirm Password:', QLineEdit(self, echoMode=[Link]))
[Link]('Phone:', QLineEdit(self))
[Link](QPushButton('Sign Up'))
# show the window
[Link]()

Py – NLU 155
156
 QCheckBox class allows you to create a checkbox widget,
which can be switched on or off.
# create a checkbox
 Usage: checkbox = QCheckBox('I agree', self)

 Checkbox emits the stateChanged signal whenever you check


or uncheck it [Link](self.on_checkbox_changed)
def on_checkbox_changed(self, value):
state = [Link](value)
if state == [Link]:
print('Checked')
elif state == [Link]:
print('Unchecked')
Py – NLU 157
QRadioButton(text[, parent=None])
 QRadioButton: used to create a radio button.

 Radio buttons that belong to the same parent belong to an


auto-exclusive group.

 Connect to the toggled() signal to trigger an action when the


radio button is switched on or off.

 Use the isChecked() method to see if the radio button is


switched on.

Py – NLU 158
def update(self):
# get the radio button the send the signal
rb = [Link]()
 Example: # check if the radio button is checked
if [Link]():
self.result_label.setText(f'You selected {[Link]()}')
label = QLabel('Please select a platform:', self)

rb_android = QRadioButton('Android', self)


rb_android.[Link]([Link])
rb_ios = QRadioButton('iOS', self)
rb_ios.[Link]([Link])
rb_windows = QRadioButton('Windows', self)
rb_windows.[Link]([Link])

self.result_label = QLabel('', self)


Py – NLU 159
 QComboBox used to create a combobox.

 Use addItem() or insertItem() to add an item to the list of the


combobox.

 Connect to the activated signal to trigger an action when the


selected item of a combobox changes.

Py – NLU 160
 Methods:

◦ addItem() – takes a string label and a data value and appends it to the
end of the list.

◦ insertItem() –like the addItem() method except that it takes an index


for the first argument and adds the item at that index to the list.

◦ currentData() – returns the currently selected item.

◦ currentIndex() – returns the index of the currently selected item.

◦ currentText() – returns the text of the currently selected item.

Py – NLU 161
def update(self):
 Example: self.result_label.setText(
f'You selected {self.cb_platform.currentText()}')
cb_label = QLabel('Please select a platform:', self)

# create a combobox
self.cb_platform = QComboBox(self)
self.cb_platform.addItem('Android')
self.cb_platform.addItem('iOS')
self.cb_platform.addItem('Windows')

self.cb_platform.[Link]([Link])

self.result_label = QLabel('', self)


Py – NLU 162
 QSpinBox presents the user with a textbox which displays an
integer with up/down button on its right.

◦ The value in the textbox increases/decreases if the up/down button is


pressed

 Use QSpinBox class to create a spin box.

 Connect to the valueChanged signal to trigger an action when


the current value of a spin box changes

Py – NLU 163
Property Description
value The current integer value of the spin box.
cleanText The current string value of the spin box (excludes the prefix
and suffix).
maximum The maximum integer value of the spin box
minimum The minimum integer value of the spin box.
prefix A string that prepends to the displayed value.
suffix A string that appends to the displayed value.
singleStep An increment/decrement integer value when up/down
arrows are clicked
wrapping A boolean value that determines whether to wrap from one
end of the range to the other when the up/down arrows are
clicked.
Py – NLU 164
 QSpinBox object emits valueChanged() signal every time when
up/down button is pressed.

amount = QSpinBox(minimum=1, maximum=100, value=20, prefix='$')


[Link]([Link])
self.result_label = QLabel('', self)

 The associated slot function can retrieve current value of the


widget by value() method.
def update(self, value):
self.result_label.setText(f'Current Value: {value}')
Py – NLU 165
 QDateEdit class used to create a date entry widget.

 QDateEdit widget allows users to edit the date using the


keyboard or up/down arrow keys to increase/decrease the
date value

 Use the date() method to get the current value of the


QDateEdit widget

 Connect to the editingFinished signal to trigger an action


when editing is finished.
Py – NLU 166
Property Description
date() Return the date displayed by the widget. The return
value has the type of QDate. If you want to convert it to
a Python [Link] object, you can use
the toPyDate() method of the QDate class.
minimumDate Specify the earliest date that can be set by the user

maximumDate Specify the latest date that can be set by the user

displayFormat is a string that formats the date displayed in the widget

Py – NLU 167
def update(self):
value = self.date_edit.date()
print(type(value))
 Example: self.result_label.setText(str([Link]()))
class MainWindow(QWidget):
def __init__(self):
super().__init__()
[Link]('PyQt QDateEdit')
[Link](200)
# create a grid layout
layout = QFormLayout()
[Link](layout)
self.date_edit = QDateEdit(self)
self.date_edit.[Link]([Link])
self.result_label = QLabel('', self)
[Link]('Date:', self.date_edit)
[Link](self.result_label)
# show the window
[Link]() Py – NLU 168
 PyQt QTimeEdit class is used to create a time entry widget

 date() method to get the current value of the QTimeEdit


widget

 Connect to the editingFinished signal to trigger an action


when editing is finished

Py – NLU 169
Property Description
time() Return the time displayed by the widget (Qtime). To
convert it to a Python [Link] object, you can use
the toPyTime() method of the QTime class.

minimumTime Specify the earliest time that can be set by the user.

maximumTime Specify the latest time that can be set by the user.

displayFormat is a string that formats the time displayed in the widget.

Py – NLU 170
 Example:
class MainWindow(QWidget):
self.result_label = QLabel('', self)
def __init__(self):
super().__init__()
[Link]('Time:', self.time_edit)
[Link](self.result_label)
[Link]('PyQt QTimeEdit')
[Link](200)
# show the window
[Link]()
# create a grid layout
layout = QFormLayout()
def update(self):
[Link](layout)
value = self.time_edit.time()
self.result_label.setText(str([Link]()))
self.time_edit = QTimeEdit(self)
self.time_edit.[Link]([Link])
Py – NLU 171
 PyQt QDateTimeEdit class is used to create a date & time entry
widget

 dateTime() method to get the current value of the


QDateTimeEdit widget

 QDateTimeEdit emits the editingFinished() signal when the


editing is finished.

 dateTimeChanged() signal can be used to trigger an action


whenever the value of the QDateTimeEdit widget changes
Py – NLU 172
Property Description
date() Return the date value displayed by the widget. The return
type is QDate. To convert it to a [Link] object,
you use the toPyDate() method of the QDate class.
time() Return the time displayed by the widget. The return value
has the type of QTime. Use the toPyTime() method to
convert it to a Python [Link] object.
dateTime() Return the date and time value displayed by the widget.
The return type is QDateTime.
minimumDate The earliest date that can be set by the user.
maximumDate The latest date that can be set by the user.

Py – NLU 173
Property Description
minimumTime The earliest time that can be set by the user.
maximumTime The latest time that can be set by the user.
minimumDateTime The earliest date & time that can be set by the
user.
maximumDateTime The latest date & time that can be set by the user.
calendarPopup Display a calendar popup if it is True.
displayFormat is a string that formats the date displayed in the
widget.
Py – NLU 174
def update(self):
 Example: value = self.datetime_edit.dateTime()
self.result_label.setText([Link]("yyyy-MM-dd HH:mm"))
class MainWindow(QWidget):
def __init__(self):
super().__init__()
[Link]('PyQt QDateTimeEdit')
[Link](200)
layout = QFormLayout()
[Link](layout)
self.datetime_edit = QDateTimeEdit(self, calendarPopup=True)
self.datetime_edit.[Link]([Link])
self.result_label = QLabel('', self)
[Link]('Date:', self.datetime_edit)
[Link](self.result_label)
[Link]() Py – NLU 175
 A slider is a widget for controlling a bounded value (a horizontal or
vertical groove).

 QSlider widget used to create a slider.

 Connect to the valueChanged signal to update the slider’s value.

 Syntax: QSlider(orientation[, parent=None])

◦ Orientation specifies the orientation of the slider. The valid values are
[Link] and [Link].

◦ Parent is the parent widget of the slider.

Py – NLU 176
 setRange() method is used to set the range of values for the slider
([Link](min,max))

◦ [Link](min)

◦ [Link](max)

 setSingleStep() method used to handle the increment/decrement of


a single step when users press the up/down or left/right arrow key

 setPageStep() method is used to handle of increment/decrement a


page step when press the page up / page down key

Py – NLU 177
 Displaying tick marks: setTickPosition() method is used to show the
tick marks
◦ horizontal slider: [Link], [Link]
◦ vertical slider: [Link], [Link]

 setTickInteral() method is used to set the interval between tick marks


(default 0)
 QSlider emits the valueChanged signal whenever the value of the
slider changes
 setValue() method is used to set a value for the slider
 value() method returns the current value of the slider

Py – NLU 178
class MainWindow(QWidget):
def __init__(self):
super().__init__()
 Example:
slider = QSlider([Link], self) [Link]('PyQt QSlider')
[Link](0, 100) [Link](200)
[Link](50)
[Link](5) # create a grid layout
[Link](10) layout = QFormLayout()
[Link]([Link]) [Link](layout)
[Link]([Link])
self.result_label = QLabel('', self)
[Link](slider)
[Link](self.result_label)
# show the window
[Link]()
def update(self, value):
self.result_label.setText(f'Current Value: Py
{value}')
– NLU 179
 PyQt QWidget: a container of other widgets

 A QWidget object is inside the main window or a parent


widget

 Set layout for the Qwidget and then add other widgets to the
container
person_pane = QWidget(self)
form_layout = QFormLayout()
person_pane.setLayout(form_layout)
form_layout.addRow('First Name:', QLineEdit(person_pane))
form_layout.addRow('Last Name:', QLineEdit(person_pane))
Py – NLU 180
 Example:

# person pane
person_pane = QWidget(self)
form_layout = QFormLayout()
person_pane.setLayout(form_layout)
form_layout.addRow('First Name:', QLineEdit(person_pane))
form_layout.addRow('Last Name:', QLineEdit(person_pane))
form_layout.addRow('Date of Birth:', QLineEdit(person_pane))
form_layout.addRow('Email Address:', QLineEdit(person_pane))
form_layout.addRow('Phone Number:', QLineEdit(person_pane))
[Link](person_pane)

Py – NLU 181
 QTabWidget used to create a tab widget

 Tabs can be movable, closable, and have different positions (North,


South, West, East)

 addTab() method is used to add a page to the tab widget

 To make the tab movable, ➔ set the movable property to True

 If the tabsClosble is true, the tabs will display a close button on


tabs

 tabShape argument is used to set the tab shape when creating a


new tab widget (rounded & triangular)
Py – NLU 182
 Example:

# create a tab widget # contact pane


tab = QTabWidget(self) contact_page = QWidget(self)
layout = QFormLayout()
# personal page contact_page.setLayout(layout)
personal_page = QWidget(self) [Link]('Phone Number:', QLineEdit(self))
layout = QFormLayout() [Link]('Email Address:', QLineEdit(self))
personal_page.setLayout(layout)
[Link]('First Name:', QLineEdit(self)) # add pane to the tab widget
[Link]('Last Name:', QLineEdit(self)) [Link](personal_page, 'Personal Info')
[Link]('DOB:', QDateEdit(self)) [Link](contact_page, 'Contact Info')

Py – NLU 183
 A widget that edits and displays both plain and rich text

 QTextEdit is used to create a widget that supports multiline


text editing and viewing

◦ The QTextEdit widget supports rich text formatting using HTML-styles


tag or Markdown format.

◦ The QTextEdit is designed to handle large documents and to respond


quickly to user input.

Py – NLU 184
 Example: class MainWindow(QWidget):
def __init__(self):
super().__init__()

[Link]('PyQt TexEdit')
[Link](200)

layout = QFormLayout()
[Link](layout)
text_edit = QTextEdit(self)
[Link](text_edit)

[Link]()

Py – NLU 185
 A progress bar widget notifies the users of the progress of an
operation and reassures them that the program is still
running.

 QProgressBar class is used to create progress bar widgets.

◦ setValue() to set the current value that reflects the percentage of the
current progress.

◦ reset() method to reset the progress bar so that it shows no progress

Py – NLU 186
 Usage: self.progress_bar = QProgressBar(self)

 A progress bar has three important values:

◦ The minimum value.

◦ The maximum value.

◦ The current step value.

Py – NLU 187
 Example:
layout = QVBoxLayout()
[Link](layout) def reset(self):
self.current_value = 0
hbox = QHBoxLayout() self.progress_bar.reset()
self.progress_bar = QProgressBar(self)
[Link](self.progress_bar) def progress(self):
if self.current_value <= self.progress_bar.maximum():
[Link](hbox) self.current_value += 5
self.progress_bar.setValue(self.current_value)
hbox = QHBoxLayout()
self.btn_progress = QPushButton('Progress', clicked=[Link])
self.bnt_reset = QPushButton('Reset', clicked=[Link])
Py – NLU 188
189
 The QMessageBox class is used to create a modal dialog that alerts
the user with important information or asks the user a question
and receives an answer.

 The QMessageBox provides some useful static methods for


displaying a message box:
◦ information() – show an information message.

◦ question() – ask the user a question and receives an answer.

◦ warning() – show a warning message.

◦ critical() – display critical information.

Py – NLU 190
 Example:
btn_question = QPushButton('Question')
btn_question.[Link]([Link]) def info(self):
[Link](
btn_info = QPushButton('Information') self, 'Information',
btn_info.[Link]([Link]) 'This is important information.'
)
btn_warning = QPushButton('Warning')
btn_warning.[Link]([Link]) def warning(self):
[Link](
btn_critical = QPushButton('Critical') self, 'Warning',
btn_critical.[Link]([Link]) 'This is a warning message.'
)

Py – NLU 191
 Example:
def question(self):
answer = [Link](
self, 'Confirmation', 'Do you want to quit?',
[Link] |
[Link]
if answer == [Link]:
[Link](
self, 'Information',
'You selected Yes. The program will be terminated.',
[Link])
[Link]() def critical(self):
else: [Link](
[Link]( self, 'Critical',
self, 'Information', 'You selected No.', 'This is a critical message.')
[Link]) Py – NLU 192
 PyQt QInputDialog class is used to create an input dialog
widget that receives input from the user

 The QInputDialog has five static methods for getting inputs:


◦ getText() – allows the user to enter a single string.

◦ getInt() – allows the user to enter an integer.

◦ getDouble() – allows the user to enter a floating point number.

◦ getMultiLineText() – allows the user to enter multiline text.

◦ getItem() – allows the user to select an item from a list.

Py – NLU 193
 Example:
# input selection
btn = QPushButton('Set Window Title')
[Link](self.open_input_dialog)

def open_input_dialog(self):
title, ok = [Link](self, 'Title Setting', 'Title:')
if ok and title:
[Link](title)

Py – NLU 194
 A file dialog allows you to select one or more files or a directory.

 QFileDialog class used to create a file dialog widget.

 Use the getOpenFileName() static method of the QFileDialog to


create a file dialog that allows users to select a single file.

 Use the getOpenFileNames() static method of the QFileDialog class


to create a file dialog that allows users to select multiple files.

 Use the getExistingDirectory() static method of the QFileDialog


class to create a file dialog that allows users to select a directory.

Py – NLU 195
 Filtering file types: To specify which types of files users are
expected to select ➔ use the setNameFilter() method

 Example:

◦ For single filter: [Link]("Images (*.png *.jpg)")

◦ For multiple filters ➔ to separate each with two semicolons: "Images


(*.png *.jpg);;Vector (*.svg)"

Py – NLU 196
 Setting views for file dialogs: The file dialog has two view modes:
list and detail.
◦ The list view shows the contents of the current directory as a list of files and
directory names

◦ The detail view displays additional information such as file sizes and modified
dates.

◦ Usage:

 [Link]([Link])

 [Link]([Link])

Py – NLU 197
 selectFiles() method: to show the file dialog

 setDirectory() method: to set the starting directory of the file


dialog

 getOpenFileName() method: select a single file

 getOpenFileNames() method: select multiple files using the

 getExistingDirectory() method: open a file dialog for selecting


a directory

Py – NLU 198
 Example:

# directory selection
dir_btn = QPushButton('Browse')
dir_btn.[Link](self.open_dir_dialog)
self.dir_name_edit = QLineEdit()

def open_dir_dialog(self):
dir_name = [Link](self, "Select a Directory")
if dir_name:
path = Path(dir_name)
self.dir_name_edit.setText(str(path))

Py – NLU 199
200
class MainWindow(QMainWindow):

 QMainWindow class used to create the main window for the application.

 setWindowTitle() method: set the title.

 setWindowIcon() method: set the window’s icon.

 setGeometry() method: set the window’s geometry including the (top,


left) coordinates, width, and height.

 menuBar() method: add a menu bar to the main window.

 setToolBar() method: set a toolbar for the main window.

 statusBar() method: add a status bar to the main window.

Py – NLU 201
Py – NLU 202
 Qt uses the QMenu class to represent a menu widget.

 menuBar() method: create a menu bar and addMenu() method


to add a new menu bar.

 addAction() method: add an item to a menu.

Py – NLU 203
 Example:
menu_bar = [Link]()

file_menu = menu_bar.addMenu('&File')
edit_menu = menu_bar.addMenu('&Edit')
help_menu = menu_bar.addMenu('&Help')

# new menu item


new_action = QAction(QIcon('./assets/[Link]'), '&New', self)
new_action.setStatusTip('Create a new document')
new_action.setShortcut('Ctrl+N')
new_action.[Link](self.new_document)
file_menu.addAction(new_action)
#…
Py – NLU 204
 Use the QToolBar class to create a new toolbar.
 addToolBar() method: add a toolbar to the main window.
 addAction() method: add an item to the toolbar.
 addSeparator() method: add a separator to the buttons
 setIconSize() method: set the icon size of the icons that appear on
the toolbar
 addWidget() method: add widgets to the toolbar
 setMovable() method: Toolbar becomes movable
 setOrientation() method: Toolbar’s orientation sets to
[Link] or [Link]

Py – NLU 205
 Example:

# new menu item


new_action = QAction(QIcon('./assets/[Link]'), '&New', self)
new_action.setStatusTip('Create a new document')
new_action.setShortcut('Ctrl+N') # toolbar
new_action.[Link](self.new_document) toolbar = QToolBar('Main ToolBar')
file_menu.addAction(new_action) [Link](toolbar)
[Link](QSize(16, 16))

[Link](new_action)
[Link](save_action)
[Link](open_action)
[Link]()
Py – NLU 206
 QStatusBar class: use to create a status bar widget.

 statusBar() method: used to create a status bar for the main


window

 showMessage() method: used to show a message on the


status bar

 addWidget() or addPermanentWidget() method: used to add a


widget to the status bar

Py – NLU 207
 Example:

# status bar def text_changed(self):


self.status_bar = [Link]() text = self.text_edit.toPlainText()
self.character_count.setText(f'Length: {len(text)}')
# display the a message in 5 seconds
self.status_bar.showMessage('Ready', 5000)

# add a permanent widget to the status bar


self.character_count = QLabel("Length: 0")
self.status_bar.addPermanentWidget(self.character_count)
Py – NLU 208
 The QDockWidget class allows you to create a widget that can
be docked inside the QMainWidow or floated as a top-level
window

 A QDockWidget has a title bar and a content area.

◦ The title bar displays the dock widget title, a float button, and a close
button.

Py – NLU 209
 Create a dock widget using the QDockWidget class:

dock = QDockWidget(tite)

 setFeatures() method of the QDockWidget object: set the dock widget


features
[Link]([Link])

 addDockWidget() method: add the dock widget to the main window

[Link]([Link], dock)

 To add widgets to a dock widget ➔ wrap the widgets inside the QWidget
and use the setWidget() method of the QDockWidget to set the widget
for the dock widget
Py – NLU 210
 Example:
# dock widget
[Link] = QDockWidget('Search')
[Link]([Link], [Link])
search_form = QWidget()
layout = QFormLayout(search_form)
search_form.setLayout(layout)
self.search_term = QLineEdit(search_form)
self.search_term.setPlaceholderText("Enter a search term")
[Link](self.search_term)
btn_search = QPushButton('Go', clicked=[Link])
[Link](btn_search)
[Link](search_form)
Py – NLU 211
212
 Use the QListWidget class allows you to create a list view widget

 The QListWidgetItem class represents the items on the list

 Methods:
◦ addItems(iterable) – adds items to the list from an iterable of strings.

◦ addItem(QListWidgetItem) – adds an item to the end of the list.

◦ insertItem(row, QListWidgetItem) – inserts an item at the specified row.

◦ takeItem(row) – removes an item from a specified row.

◦ clear() – removes and deletes all items from the list.

Py – NLU 213
self.list_widget = QListWidget(self)
self.list_widget.addItems(['Learn Python', 'Master PyQt’])

def add(self):
 Example: text, ok = [Link](self, 'Add a New Wish', 'New Wish:')
if ok and text:
self.list_widget.addItem(text)
def insert(self):
text, ok = [Link](self, 'Insert a New Wish', 'New Wish:')
if ok and text:
current_row = self.list_widget.currentRow()
self.list_widget.insertItem(current_row+1, text)
def remove(self):
current_row = self.list_widget.currentRow()
if current_row >= 0:
current_item = self.list_widget.takeItem(current_row)
del current_item
def clear(self):
self.list_widget.clear() Py – NLU 214
 The QTableWidget class allows you to create a table widget that
displays the tabular form of items.

 Use the QTableWidgetItem class to create a table item.

 Methods:
◦ setColumnCount() and setRowCount() methods to set the columns and rows
for the table.

◦ setHorizontalHeaderLabels() method to set the horizontal headers for the


table.

◦ Use the setItem() method to set an item for the table.

Py – NLU 215
 The QTableWidget class allows you to create a table widget
that displays the tabular form of items.

 Use the QTableWidgetItem class to create a table item.

 Methods:
◦ …

◦ Use the currentRow() method to get the currently selected row.

◦ Use the insertRow() method to insert a new row into the table.

◦ Use the deleteRow() method to delete a row from the table.

Py – NLU 216
 Example:
[Link] = QTableWidget(self)
[Link]([Link])
[Link](3)
[Link](0, 150)
[Link](1, 150)
[Link](2, 50)
[Link](employees[0].keys())
[Link](len(employees))
row = 0
for e in employees:
[Link](row, 0, QTableWidgetItem(e['First Name']))
[Link](row, 1, QTableWidgetItem(e['Last Name']))
[Link](row, 2, QTableWidgetItem(str(e['Age'])))
row += 1 Py – NLU 217
 The QTreeWidget class allows you to create a tree view widget that
consists of items.
◦ The QTreeWidgetItem class represents the item of the tree.

 Methods:
◦ setColumnCount() method of the QTreeWidget class to set the columns for the
tree.

◦ setHeaderLabels() method of the QTreeWidget class to set the column headers of


the tree.

◦ addChild() method of the QTreeWidgetItem to establish the parent/child


relationship between items.

Py – NLU 218
 Example:
# tree
tree = QTreeWidget(self)
[Link](2)
[Link](['Departments', 'Employees'])
departments = ['Sales', 'Marketing', 'HR'] # addition data to the tree
employees = { for department in departments:
'Sales': ['John', 'Jane', 'Peter'], department_item = QTreeWidgetItem(tree)
'Marketing': ['Alice', 'Bob'], department_item.setText(0, department)
'HR': ['David'], # set the child
} for employee in employees[department]:
employee_item = QTreeWidgetItem(tree)
employee_item.setText(1, employee)
department_item.addChild(employee_item)
Py – NLU 219
220
 Qt Style Sheets or QSS is very much similar to Cascading Style
Sheets (CSS) for the web.

◦ QSS supports only a limited number of rules in comparison with CSS

 Use setStyleSheet() method with a style sheet string to set the


style sheets for a widget

Py – NLU 221
 Apply QSS to an application

if __name__ == '__main__':

app = QApplication([Link])
[Link](Path('[Link]').read_text())
window = MainWindow()
[Link]([Link]())

Py – NLU 222
QLabel#subheading {
QPushButton {
 File [Link] color: #0f1925; background-color:
font-size: 12px; #0d6efd;
font-weight: normal; color: #fff;
QWidget { margin-bottom: 10px; font-weight: 600;
background-color: #fff; } border-radius: 8px;
} QLineEdit { border: 1px solid #0d6efd;
QLabel { border-radius: 8px; padding: 5px 15px;
color: #464d55; border: 1px solid #e0e4e7;
margin-top: 10px;
font-weight: 600; padding: 5px 15px;
}
outline: 0px;
} }
QLabel#heading { QLineEdit:focus { QPushButton:hover,
color: #0f1925; border: 1px solid #d0e3ff; QPushButton:focus {
font-size: 18px; } background-color:
margin-bottom: 10px; QLineEdit::placeholder { #0b5ed7;
} color: #767e89; border: 3px solid #9ac3fe;
} }

Py – NLU 223
FACULTY OF INFORMATION TECHNOLOGY

You might also like