Python4 GUI6
Python4 GUI6
Semester 1, 2025/2026
Introduction to GUI in Python
◦ Advanced components
◦ Advanced components
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.
◦ import tkinter as tk
◦ from tk import *
Py – NLU 4
Tkinter gives you the ability to create Windows with widgets in
them
Py – NLU 5
Tkinter → tkinter tkSimpleDialog → [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
Py – NLU 11
There are some common attributes of all the widgets:
◦ Anchors: Controls where the text/contents are anchored inside 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!
[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")
geometry()
Py – NLU 16
[Link]()
Py – NLU 17
General form for all widgets:
◦ [Link]()
Py – NLU 18
This widget is used to display the text or images.
w = Label(parent, option, . . . . . )
Where,
◦ 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
Where,
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
◦ 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:
[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).
◦ variable: the control variable that tracks the current state of the checkbutton
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
Syntax:
◦ current_var = [Link]()
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
◦ variable: The control variable that this radiobutton shares with the
other radiobuttons in the group,
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,
◦ 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.
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)
[Link](name="int", value=100)
[Link](name="str", value=“FIT")
[Link](name="bool", value=False)
[Link](name="float", value=1.236)
[Link](name="int", value=100)
[Link](name="str", value="GFG")
[Link](name="bool", value=False)
[Link](name="float", value=1.236)
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
◦ 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:
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]
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.
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.
◦ 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.
◦ 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.
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.
◦ options − the list of most commonly used options for this widget, can
be used as key-value pairs separated by commas.
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;
Py – NLU 65
Example:
class ScrollbarGUI:
def __init__(self):
root = Tk()
scrollbar = Scrollbar(root)
[Link](side=RIGHT, fill=Y)
[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.
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.
◦ options: bg, fg, bd – border, orient (vertical or horizontal), from, to, troughcolor,
state, sliderlength, label, highlightbackground, cursor, circle, dot, etc.
Methods:
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.
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
◦ fill: determines if a widget will occupy the available space (X, Y, or BOTH)
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:
◦ columnspan, rowspan: a widget can span more than one cell in the grid
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.
Py – NLU 79
Absolute positioning: [Link](x=50, y=50)
Relative positioning:
[Link](relx=0.5, rely=0.5,
anchor=CENTER)
◦ [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
Py – NLU 82
Use messagebox method in the Tkinter to create alert boxes
◦ 0, otherwise
Py – NLU 83
class ImageGUI:
def __init__(self):
window = [Link]()
[Link]("GUI")
icon = [Link](file=“[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.
◦ 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.
◦ askquestion() – To display a dialog box that asks with two options YES or NO.
Py – NLU 88
Tkinter provide a library like messagebox.
◦ 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.
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.
◦ 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
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.
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.
Shift True when the user is holding down the shift key.
Py – NLU 100
Events that occur as a result of user interaction with a mouse
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:
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():
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
Py – NLU 112
Build an application to manage todo list:
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.
Py – NLU 115
116
Qt is a cross platform GUI application development framework
written in C++.
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.
Py – NLU 121
Every PyQt application needs one instance of QApplication
class.
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:
Py – NLU 124
A signal is a special property of an object that is emitted when
an event occurs.
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
button = QPushButton('Delete')
QPushButton with image: [Link](QIcon('[Link]'))
◦ No arguments.
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__()
◦ Use the echoMode property to change the way the text is displayed.
Py – NLU 135
136
QHBoxLayout lays out widgets in a horizontal row, from left to
right
Py – NLU 137
QGridLayout lays out widgets in a two-dimensional grid.
Widgets can occupy multiple cells
Py – NLU 138
QHBoxLayout divides the parent widget into horizontal boxes
and places the child widgets sequentially from left to right.
Step by step:
◦ 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
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
Py – NLU 143
Alignments
By default, the QHBoxLayout sets specific left, top, right, and bottom
margins for child widgets.
Py – NLU 144
QVBoxLayout divides the parent widget into vertical boxes
and places the child widgets sequentially from top to bottom
◦ 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:
Py – NLU 147
Alignment:
in the QVBoxLayout
Py – NLU 148
Alignment:
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.
Py – NLU 151
Alignment Flag:
◦ AlignJustify: Justifies the text in the available space.
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)
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)
Py – NLU 160
Methods:
◦ addItem() – takes a string label and a data value and appends it to the
end of the list.
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])
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.
maximumDate Specify the latest date that can be set by the user
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
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.
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
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).
◦ Orientation specifies the orientation of the slider. The valid values are
[Link] and [Link].
Py – NLU 176
setRange() method is used to set the range of values for the slider
([Link](min,max))
◦ [Link](min)
◦ [Link](max)
Py – NLU 177
Displaying tick marks: setTickPosition() method is used to show the
tick marks
◦ horizontal slider: [Link], [Link]
◦ vertical slider: [Link], [Link]
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
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
Py – NLU 183
A widget that edits and displays both plain and rich text
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.
◦ setValue() to set the current value that reflects the percentage of the
current progress.
Py – NLU 186
Usage: self.progress_bar = QProgressBar(self)
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.
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
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.
Py – NLU 195
Filtering file types: To specify which types of files users are
expected to select ➔ use the setNameFilter() method
Example:
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
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.
Py – NLU 201
Py – NLU 202
Qt uses the QMenu class to represent a menu widget.
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')
Py – NLU 205
Example:
[Link](new_action)
[Link](save_action)
[Link](open_action)
[Link]()
Py – NLU 206
QStatusBar class: use to create a status bar widget.
Py – NLU 207
Example:
◦ 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)
[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
Methods:
◦ addItems(iterable) – adds items to the list from an iterable of strings.
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.
Methods:
◦ setColumnCount() and setRowCount() methods to set the columns and rows
for the table.
Py – NLU 215
The QTableWidget class allows you to create a table widget
that displays the tabular form of items.
Methods:
◦ …
◦ Use the insertRow() method to insert a new row into 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.
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.
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