UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 1
REGULAR EXPRESSIONS
Concept of Regular Expression(REgEX)
Regular Expression is a sequence of characters that define a search pattern
Patterns are used by string searching algorithms for “find” or “find and
replace”operations on strings or for input validation.
Regular expressions are patterns used to search, match, and manipulate strings.
Python provides the re module to work with regex.
The regular expression library “re” must be imported into out program before we
can use it.
import re
• Ex 1: We can write a regular expression to represent all mobile numbers. (I.E.,
All mobile numbers having aParticular format i.E., Exactly 10 numbers only)
• Ex 2: we can write a regular expression to represent all mail ids.
Basic Functions in re Module
FUNCTION DESCRIPTION
[Link](pattern, string) Matches pattern at the beginning of the string
[Link](pattern, string) Searches pattern anywhere in the string
[Link](pattern, string) Returns a list of all matches
[Link](pattern, string) Returns an iterator of match objects
[Link](pattern, replace, string) Replaces matches with given text
[Link](pattern, string) Splits string by the given pattern
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 2
META CHARACTERS
Meta
Description Example
Character
. Matches any single character except newline "a.c" matches "abc", "axc"
^ Matches the beginning of a string "^Hello" matches "Hello World"
$ Matches the end of a string "World$" matches "Hello World"
* 0 or more occurrences "ab*" matches "a", "ab", "abb"
+ 1 or more occurrences "ab+" matches "ab", "abb"
? 0 or 1 occurrence "ab?" matches "a", "ab"
{n} Exactly n occurrences "a{3}" matches "aaa"
{n,} n or more occurrences "a{2,}" matches "aa", "aaa"
{n,m} Between n and m occurrences "a{2,4}" matches "aa", "aaa", "aaaa"
[] Matches any one character inside "[aeiou]" matches vowels
[^ ] Negation – matches characters not inside "[^0-9]" matches non-digits
\d Matches a digit (0–9) \d matches "123"
\D Matches a non-digit \D matches "abc"
\w Matches word character (letters, digits, _) \w matches "hello_123"
\W Matches non-word characters \W matches "@"
\s Matches whitespace (space, tab, newline) \s matches " "
\S Matches non-whitespace \S matches "Python"
\b Matches word boundary \bcat\b matches "cat" but not "scatter"
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 3
USING MATCH() FUNCTION
[Link] method in python is used to check if a given pattern matches the
beginning of a string.
it’s like searching for a word or pattern at the start of a sentence.
For example, we can use [Link] to check if a string starts with a certain word,
number, or symbol.
SYNTAX:
[Link](pattern, string, flags=0)
EXAMPLE:# checking if the string starts with "hello"
import re
s = "hello, world!"
match = [Link](“Hello", s)
if match:
print("pattern found!")
else:
print("pattern not found.")
OUTPUT:
Pattern found
EXAMPLE:# checking if the string not starts with "hello"
import re
s = "hello, world!"
match = [Link](“World", s)
if match:
print("pattern found!")
else:
print("pattern not found.")
OUTPUT:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 4
Pattern not found
EXAMPLE:# Checking if the string starts with a number
import re
s = "123abc"
match = [Link](r"\d", s) #/d – matches digits
if match:
print("Starts with a number.")
else:
print("Doesn't start with a number.")
OUTPUT:
starts with a number.
EXAMPLE:# Extracting string
import re
text = "Hello123"
m = [Link](r"[A-Za-z]+", text) #+ -1 or more occurences
print(m) # Match object
print([Link]()) # Actual matched text
OUTPUT:
<[Link] object; span=(0, 5), match='Hello'>
Hello
The group() method is used on that match object to extract the actual part of the string
that matched the pattern.
EXAMPLE:Extracting dates
import re
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 5
text = "2025-09-19"
m = [Link](r"(\d{4})-(\d{2})-(\d{2})", text)
print("Full match:", [Link](0))
print("Year:", [Link](1))
print("Month:", [Link](2))
print("Day:", [Link](3))
OUTPUT:
Full match: 2025-09-19
Year: 2025
Month: 09
Day: 19
EXAMPLE:Searching starting string using metacharacters
import re
text = "Welcome to Python"
m = [Link](r"^Welcome", text) # ^ - starting of string
print("Matched:", [Link]())
OUTPUT:
Matched: Welcome
EXAMPLE: only alphabets followed by digits
import re
text = "abc123"
m = [Link](r"^[a-z]+[0-9]+$", text) #$- Ending of string
print("Matched:", [Link]())
OUTPUT:
Matched: abc123
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 6
SEARCH()
The [Link]() function in python's re module is used to scans the entire string and
returns a match object if a match is found, otherwise, it returns none.
Syntax of [Link]()
[Link](pattern, string, flags=0)
Parameters:
• pattern: A regex pattern to search for; can be simple text or a complex
expression.
• string: The target string where the pattern is searched.
• flags (optional): Modifiers that change matching behavior (e.G., Case-
insensitive); default is 0.
EXAMPLE: Search for text anywhere
import re
s = "Hello, welcome to the world of Python."
pat = "welcome" # pattern
res = [Link](pat, s) # search pattern
if res:
print("Yes")
else:
print("No")
OUTPUT:
Yes
EXAMPLE: Search for digits
import re
text = "Order number is 98765"
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 7
m = [Link](r"\d+", text) # \d+ → one or more digits
print("First number found:", [Link]())
OUTPUT:
First number found: 98765
EXAMPLE: Search for words starting with capital letter
import re
text = "today we learn Python regex"
m = [Link](r"[A-Z][a-z]+", text)
print("Found:", [Link]())
OUTPUT:
Found: Python
EXAMPLE: Search using ^ and $ (with search)
import re
text = "Welcome to Python"
m = [Link](r"^Welcome", text) # start of string
print("Matched:", [Link]())
m2 = [Link](r"Python$", text) # end of string
print("Matched:", [Link]())
OUTPUT:
Matched: Welcome
Matched: Python
EXAMPLE:
import re
text = "Email: test@[Link]"
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 8
m = [Link](r"(?P<user>\w+)@(?P<domain>\w+\.\w+)", text)
print("User:", [Link]("user")) #0 or 1 occurence
print("Domain:", [Link]("domain"))
OUTPUT:
User: test
Domain: [Link]
FINDALL()
• [Link]() method in python helps us find all pattern occurrences in a string.
• it's like searching through a sentence to find every word that matches a specific
rule.
Syntax of [Link]()
result = [Link](pattern, string)
Parameters
pattern: the regular expression pattern we are looking for.
string: The string where we want to search for the pattern.
result: This will be a list of all occurrences of the pattern in the string.
EXAMPLE: Find all digits in a string
import re
text = "My numbers are 45, 789 and 1001"
result = [Link](r"\d+", text) # \d+ → one or more digits
print(result)
OUTPUT:
['45', '789', '1001’]
EXAMPLE:Find all words
import re
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 9
text = "Python is easy to learn"
result = [Link](r"[A-Za-z]+", text)
print(result)
OUTPUT:
['Python', 'is', 'easy', 'to', 'learn']
EXAMPLE:Find all vowels
import re
text = "Regular Expressions in Python"
result = [Link](r"[aeiouAEIOU]", text)
print(result)
OUTPUT:
['e', 'u', 'a', 'E', 'o', 'i', 'o']
EXAMPLE:Find all words starting with capital letters
import re
text = "India Won the Cricket WorldCup in 2025"
result = [Link](r"[A-Z][a-z]+", text)
print(result)
OUTPUT:
['India', 'Won', 'Cricket', 'WorldCup']
EXAMPLE:Find all two-letter words
import re
text = "We go to an AI lab"
result = [Link](r"\b\w{2}\b", text)
print(result)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 10
OUTPUT:
['We', 'go', 'to', 'an', 'AI']
EXAMPLE:Find all numbers with 3 or more digits
import re
text = "Pin codes: 123, 9876, 45, 10001"
result = [Link](r"\d{3,}", text)
print(result)
OUTPUT:
['123', '9876', '10001']
SUB() FUNCTION
The sub() function replaces the matches with the text of your choice:
SYNTAX:
[Link](pattern, repl, string, count=0, flags=0)
EXAMPLE:Simple word replacement
import re
text = "Today is rainy"
result = [Link](r"rainy", "sunny", text)
print(result)
OUTPUT:
Today is sunny
EXAMPLE:Replace digits with a #
import re
text = "My phone number is 9876543210"
result = [Link](r"\d", "#", text)
print(result)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 11
OUTPUT:
My phone number is ##########
EXAMPLE:Replace multiple spaces with a single space
import re
text = "Python is fun"
result = [Link](r"\s+", " ", text)
print(result)
OUTPUT:
Python is fun
EXAMPLE:Replace first two digits only (using count)
import re
text = "123 456 789"
result = [Link](r"\d", "*", text, count=2)
print(result)
OUTPUT:
**3 456 789
EXAMPLE:Replacing special characters with empty string
import re
text = "Hello@World!2025#Regex"
result = [Link](r"[^A-Za-z0-9 ]", "", text)
print(result)
OUTPUT:
HelloWorld2025Regex
SPLIT() FUNCTION
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 12
The split() function returns a list where the string has been split at each match:
SYNTAX:
[Link](pattern, string, maxsplit=0, flags=0)
Parameters:
• pattern (required): this regular expression pattern that defines where the string
should be split.
• string (required): this input string to be split based on the given pattern.
• maxsplit (optional, default is 0): this maximum number of splits to
perform; 0 means no limit.
EXAMPLE:Split using spaces
import re
text = "Python is easy to learn"
result = [Link](r"\s", text) # \s → whitespace
print(result)
OUTPUT:
['Python', 'is', 'easy', 'to', 'learn']
EXAMPLE:Split using multiple delimiters (comma, semicolon, space)
import re
text = "apple,banana;orange grape"
result = [Link](r"[,; ]", text)
print(result)
OUTPUT:
['apple', 'banana', 'orange', 'grape']
EXAMPLE:Split using digits
import re
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 13
text = "abc123xyz456pqr"
result = [Link](r"\d+", text) # split at digits
print(result)
OUTPUT:
['abc', 'xyz', 'pqr']
EXAMPLE:Split using word boundaries
import re
text = "HelloWorldPython"
result = [Link](r"(?=[A-Z])", text) # split before capital letters
print(result)
OUTPUT:
['', 'Hello', 'World', 'Python’]
(?=[A-Z]) → lookahead assertion, meaning “split at a position that is immediately
followed by a capital letter.”
EXAMPLE:Using maxsplit (limit number of splits)
import re
text = "one two three four five"
result = [Link](r"\s", text, maxsplit=2)
print(result)
OUTPUT:
['one', 'two', 'three four five']
EXAMPLE:Split at non-alphanumeric characters
import re
text = "Hello@World!Regex-2025"
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 14
result = [Link](r"\W+", text) # \W → non-word characters
print(result)
OUTPUT:
['Hello', 'World', 'Regex', '2025']
EXAMPLE:Split on newlines
import re
text = "Line1\nLine2\nLine3"
result = [Link](r"\n", text)
print(result)
OUTPUT:
['Line1', 'Line2', 'Line3']
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 15
GUI PROGRAMMING IN PYTHON(USING TKINTER)
GUI (Graphical User Interface):
A way for users to interact with applications using graphical elements (windows,
buttons, text fields, etc.) Instead of text commands.
Tkinter is python’s standard GUI library.
Comes pre-installed with python.
Provides tools to build windows, dialogs, menus, and widgets like button, label,
entry, text, checkbutton, radiobutton, etc.
Python tkinter is the fastest and easiest way to create GUI applications.
Creating a gui using tkinter is an easy task.
INTRODUCTION TO GUI LIBRARY
What is Tkinter?
• Tkinter is python’s standard library for GUI (graphical user interface)
programming.
• It provides tools (called widgets) like buttons, labels, text boxes, menus, etc., To
build desktop applications.
• Tkinter is built on top of the tcl/tk gui framework, which is lightweight and
cross-platform (works on windows, macos, linux).
• Since tkinter is included in python by default, no extra installation is needed.
Why use Tkinter?
Easy to use — good for beginners.
Comes with python (no need to install external libraries).
Cross-platform (runs on all os).
Provides enough widgets to make functional desktop apps.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 16
Can be extended with additional libraries (like ttk for themed widgets).
Using Tkinter to Create Desktop Applications
The basic steps of creating a simple desktop application using the tkinter module in
python are as follows:
• First of all, import the tkinter module.
• The second step would be to create a basic window for the desktop Application.
• Then you can add different gui components to the window and Functionality to these
components or widgets.
• Then enter the main event loop using mainloop() function to run the Desktop
application.
Basic Tkinter program in Python
import tkinter # imports the tkinter module (Python's GUI library)
root = [Link]() # creates the main window (the root window of your app)
[Link]() # starts the event loop (keeps the window open and responsive)
When you run this code:
• A blank window will open (default size ~200x200 pixels).
• Tk() instance in your program.
• [Link]() keeps the program running until you close the window
manually. Without it, the window would appear and close immediately
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 17
Tkinter program by setting a window title!
import tkinter
root=[Link]()
[Link]("Welcome")
[Link]()
Frame at center
import tkinter
root = [Link]()
[Link]('welcome')
w = 400
h = 300
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate x, y for centering
x = (ws - w) // 2
y = (hs - h) // 2
[Link]('%dx%d+%d+%d' % (w, h, x, y))
[Link]()
Background color
import tkinter
root = [Link]()
[Link]('welcome')
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 18
w = 400
h = 300
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws - w) // 2
y = (hs - h) // 2
[Link]('%dx%d+%d+%d' % (w, h, x, y))
[Link](background="#000000")
[Link]()
1. pack()
• Simple & automatic layout.
• Places widgets relative to each other (top, bottom, left, right).
• You don’t need to give exact positions.
• Example: stacking buttons.
2. grid()
• Table-like layout (rows & columns).
• You specify the row and column for each widget.
• More control than pack().
3. place()
• Absolute positioning (you give exact x, y coordinates).
• Or relative positioning with relx, rely, relwidth, relheight (values between 0.0
and 1.0).
LAYOUT MANAGEMENT WITH PACK,GRID AND PLACE
In python's tkinter library pack, grid, and place are the three primary geometry
managers used for arranging widgets within a window or frame.
Each offers a distinct approach to layout management.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 19
1)PACK
• Pack() is one of the geometry managers in tkinter.
• It automatically arranges widgets inside their parent (like root or a frame).
• Instead of specifying rows and columns (like grid), it places widgets relative to
each other.
How does it work?
• By default, widgets are stacked vertically (top to bottom).
• But you can control where they go using options like:
• Side → where to place the widget (TOP, BOTTOM, LEFT, RIGHT).
• Fill → expand to fill available space (x, y, both).
• Expand → tells the widget to expand if there’s extra space.
• padx, pady → add space outside the widget.
Example 1: Simple pack()
import tkinter as tk
Buttons will appear one
root = [Link]()
below another (top →
[Link]("Pack Example") bottom).
btn1 = [Link](root, text="Button 1")
[Link]() # placed at top by default
btn2 = [Link](root, text="Button 2")
[Link]()
btn3 = [Link](root, text="Button 3")
[Link]()
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 20
Example 2: Using side
import tkinter as tk
root = [Link]()
[Link]("Pack with side")
btn1 = [Link](root, text="Left")
[Link](side="left")
btn2 = [Link](root, text="Right")
[Link](side="right")
btn3 = [Link](root, text="Top")
[Link](side="top")
btn4 = [Link](root, text="Bottom")
[Link](side="bottom")
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 21
Example 3: Using fill and expand
import tkinter as tk widgets stretch and expand.
import tkinter as tk
root = [Link]()
[Link]("Pack with Fill & Expand")
btn1 = [Link](root, text="Fill X")
[Link](fill="x") # stretches horizontally
btn2 = [Link](root, text="Fill Y")
[Link](side="left", fill="y") # stretches vertically
btn3 = [Link](root, text="Expand Both")
[Link](expand=True, fill="both") # fills empty space
[Link]()
Example 4: Using padx,pady
import tkinter as tk
root = [Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 22
[Link]("padx & pady Example")
[Link]("300x200")
# Button with horizontal padding
btn1 = [Link](root, text="Button 1")
[Link](padx=50, pady=10) # 50px space left & right, 10px space top & bottom
# Button with more vertical padding
btn2 = [Link](root, text="Button 2")
[Link](padx=20, pady=30) # 20px side space, 30px top & bottom space
# Button without extra padding
btn3 = [Link](root, text="Button 3")
[Link]() # default (no extra padding)
[Link]()
Explanation
• padx = adds extra space left and right of the widget.
• pady = adds extra space top and bottom of the widget.
example:
• [Link](padx=50, pady=10) → button 1 will have 50 pixels of empty
space on left and right, and 10 pixels above and below.
• [Link](padx=20, pady=30) → button 2 will look like it’s floating
because of bigger vertical spacing.
• [Link]() → no padding, sits close to others.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 23
2)GRID
• Grid is a geometry manager in tkinter.
• It arranges widgets in a table-like structure (rows × columns).
• Instead of stacking (pack) or giving coordinates (place), you tell tkinter which
row and column to put the widget in.
SYNTAX:
[Link](row=r, column=c, padx= , pady= , columnspan= , rowspan= )
• row → row number (starts from 0)
• column → column number (starts from 0)
• padx, pady → extra spacing outside widget.
• columnspan → make widget stretch across multiple columns.
• rowspan → make widget stretch across multiple rows.
Rowspan and columnspan are used when you want a widget to occupy more than one
row or more than one column in the grid layout.
Example 1: Simple Grid Layout
import tkinter as tk
root = [Link]()
[Link]("Grid Example")
# Row 0
[Link](root, text="Name").grid(row=0, column=0, padx=10, pady=5)
[Link](root).grid(row=0, column=1, padx=10, pady=5)
# Row 1
[Link](root, text="Age").grid(row=1, column=0, padx=10, pady=5)
[Link](root).grid(row=1, column=1, padx=10, pady=5)
# Row 2
[Link](root, text="Submit").grid(row=2, column=0, columnspan=2, pady=10)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 24
[Link]()
Example 2: Calculator-Style Grid
import tkinter as tk
root = [Link]()
[Link]("Calculator Grid")
btn1 = [Link](root, text="1", width=5)
[Link](row=0, column=0, padx=5, pady=5)
btn2 = [Link](root, text="2", width=5)
[Link](row=0, column=1, padx=5, pady=5)
btn3 = [Link](root, text="3", width=5)
[Link](row=0, column=2, padx=5, pady=5)
btn4 = [Link](root, text="4", width=5)
[Link](row=1, column=0, padx=5, pady=5)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 25
btn5 = [Link](root, text="5", width=5)
[Link](row=1, column=1, padx=5, pady=5)
btn6 = [Link](root, text="6", width=5)
[Link](row=1, column=2, padx=5, pady=5)
[Link]()
3)PLACE
• Place is a geometry manager in tkinter.
• It allows you to position widgets at exact coordinates (x, y) or relative
positions (relx, rely).
• Unlike pack (stacking) or grid (rows & columns), place gives absolute control
of positioning.
SYNTAX:
[Link](x= , y= , width= , height= , relx= , rely= , relwidth= , relheight= )
• x, y → absolute pixel positions.
• width, height → fixed size of widget.
• relx, rely → relative position (0.0 to 1.0). example: relx=0.5 means middle of
width.
• relwidth, relheight → relative size (percentage of parent window).
parameters of .place()
• relx → relative position of the widget along the x-axis (horizontal).
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 26
• value is between 0.0 and 1.0.
• 0.0 means left edge of parent, 1.0 means right edge.
• example: relx=0.5 means widget is placed at the horizontal center.
• rely → relative position of the widget along the y-axis (vertical).
• value is between 0.0 and 1.0.
• 0.0 means top edge, 1.0 means bottom edge.
• example: rely=0.5 means widget is at the vertical center.
• relwidth → relative width of the widget compared to the parent.
• value is between 0.0 and 1.0.
• example: relwidth=0.5 means the widget’s width is 50% of parent
width.
• relheight → relative height of the widget compared to the parent.
• value is between 0.0 and 1.0.
• example: relheight=0.25 means the widget’s height is 25% of parent
height.
Example 1: Absolute Positioning
Buttons placed exactly where you tell them.
import tkinter as tk
root = [Link]()
[Link]("Place Example")
[Link]("300x200")
btn1 = [Link](root, text="Button 1")
[Link](x=50, y=50) # Position at (50,50)
btn2 = [Link](root, text="Button 2")
[Link](x=150, y=100) # Position at (150,100)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 27
Example 2: RELATIVE Positioning
import tkinter as tk
Button stays in the center, even if you resize the
root = [Link]() window.
[Link]("Relative Place Example")
[Link]("300x200")
btn = [Link](root, text="Centered Button")
[Link](relx=0.5, rely=0.5, anchor="center")
# Center of window (50% width, 50% height)
[Link]()
Example 3: Resizable Widget
import tkinter as tk
root = [Link]()
[Link]("Place Resize Example")
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 28
[Link]("300x200")
label = [Link](root, text="Full Width Label", bg="lightblue")
[Link](relx=0, rely=0, relwidth=1, height=30)
# Stretches full width at top
[Link]()
Choosing the Right Manager:
• pack(): Best for simple, linear layouts (e.G., Toolbars, menus)stack widget
horizontally/vertically.
• grid(): Ideal for structured, tabular layouts (e.G., Forms, data displays).
• place(): Use when precise, absolute positioning is necessary or for overlaying
widgets.
Important Note:
Avoid mixing pack() and grid() within the same parent widget, as this can lead to
unexpected behavior and layout conflicts. While place() can be used alongside
either pack() or grid() within the same parent, careful management is required to
prevent overlapping.
WIDGET WITH THEIR ATTRIBUTES
What are Widgets in Tkinter?
• In tkinter, a widget is essentially a graphical component that the user can interact
with.
• They can range from simple elements like buttons and labels to more complex
ones like text entry fields, listboxes, and canvases.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 29
• Each widget serves a specific purpose and can be customized to fit the design
and functionality requirements of your application.
FRAME
A frame is a rectangular container used to group and organize other widgets.
It is often used as a layout manager helper to structure GUIs into logical sections.
Syntax
frame = [Link](master, option=value, ...)
• master → The parent widget (like root or another frame).
• option=value → Attributes of the frame.
Common Attributes of Frame
Attribute Description Example
bg / background Background color of the frame bg="lightblue"
bd / borderwidth Width of the border (default = 0) bd=5
Relief Type of border style relief="raised"
Height Height of the frame (in pixels) height=200
Width Width of the frame (in pixels) width=300
Mouse pointer shape when hovering over
Cursor cursor="hand2"
frame
Highlightbackground Border color when not focused highlightbackground="red"
Highlightcolor Border color when focused highlightcolor="green"
Highlightthickness Thickness of the highlight border highlightthickness=3
padx / pady Internal padding (inside frame) padx=10, pady=10
Example:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 30
import tkinter as tk
root = [Link]()
[Link]("frame example")
# creating a frame with attributes
frame1 = [Link](root,
bg="lightblue",
bd=5,
relief="ridge",
width=300,
height=150,
cursor="hand2",
highlightbackground="red",
highlightcolor="green",
highlightthickness=2)
[Link](padx=20, pady=20)
# adding a label inside the frame
label = [Link](frame1, text="this is inside a frame", bg="lightblue", font=("arial",
12))
[Link]()
[Link]()
LABEL
In tkinter, the label widget is used to display text or images in a window.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 31
It’s a very common widget for showing information (like headings, messages, or
instructions).
Syntax:
• Label = label(parent, option=value, ...)
• Parent → the container (usually root window or frame).
• Options (attributes) → customize the label.
COMMON ATTRIBUTES OF LABEL
Attribute Description Example
text Text to display on label Label(root, text="Hello")
font Font style, size, type font=("Arial", 16, "bold")
Fg Foreground (text) color fg="blue"
Bg Background color bg="yellow"
image Display an image (e.g., PhotoImage) image=photo
compound Show both text and image compound="left"
padx, pady Internal padding (space inside) padx=10, pady=5
width, height Dimensions of label width=20, height=2
anchor Position of text inside label (n, s, e, w, anchor="w"
center)
relief Border style (flat, raised, sunken, relief="sunken"
groove, ridge)
cursor Mouse cursor shape when hovered cursor="hand2"
Align multiple lines of text (left, right,
justify justify="left"
center)
borderwidth (bd) Thickness of border bd=5
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 32
Example:
import tkinter as tk
root = [Link]()
[Link]("Label Example")
# Simple label with text
label1 = [Link](root, text="Hello, Tkinter!", font=("Arial", 16), fg="white",
bg="blue", padx=10, pady=5)
[Link](pady=10)
# Label with border and anchor
label2 = [Link](root, text="Left Aligned Text", width=30, height=2, relief="ridge",
anchor="w")
[Link](pady=10)
[Link]()
BUTTON
• The button widget is used to create a clickable button in a GUI, which can
perform an action (like opening a file, submitting a form, exiting a program,
etc.).
Syntax:
button = button(parent, option=value, ...)
• Parent → the container (root window or frame).
• Options (attributes) → customize the button.
COMMON ATTRIBUTES OF BUTTON
Attribute Description Example
Text Text to display on button text="Click Me"
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 33
Font Font style, size, type font=("Arial", 14, "bold")
Fg Foreground (text) color fg="white"
Bg Background color bg="green"
width, height Dimensions of button width=20, height=2
padx, pady Internal padding (space inside) padx=5, pady=5
Image Add an image instead of text image=photo
Show both text and image (top,
Compound compound="left"
bottom, left, right)
Border style (flat, raised, sunken,
Relief relief="raised"
groove, ridge)
borderwidth (bd) Thickness of button border bd=5
State Button state: NORMAL, state="disabled"
DISABLED, ACTIVE
Cursor Mouse cursor shape when cursor="hand2"
Hovered
Command Function to call when button is command=my_function
Clicked
activebackground Background color when button is activebackground="yellow"
clicked
activeforeground Text color when button is clicked activeforeground="red"
Example:
import tkinter as tk
def say_hello():
print("Hello, Tkinter!")
root = [Link]()
[Link]("Button Example")
# Simple button
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 34
btn1 = [Link](root, text="Click Me", font=("Arial", 14), bg="blue", fg="white",
command=say_hello)
[Link](pady=10)
# Disabled button
btn2 = [Link](root, text="Disabled Button", state="disabled", width=20, height=2)
[Link](pady=10)
CHECK BUTTON
In tkinter, a checkbutton widget is used to create a check box — a small square box
that can be checked (✓) or unchecked, often used to take multiple choices from the
user.
Syntax
check = checkbutton(master, options...)
Common Attributes of Checkbutton:
Attribute Description Example
Master Parent window/frame in which the widget root, frame1
is placed
Text Text label displayed beside the checkbox text="Accept Terms"
Variable Tkinter variable (IntVar, StringVar, variable=var1
BooleanVar) that stores the checkbox state
Onvalue Value stored in variable when checkbox is onvalue=1
checked
Offvalue Value stored in variable when checkbox is offvalue=0
unchecked
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 35
Command Function to call when checkbox state command=show_status
changes
bg / background Background color bg="lightblue"
fg / foreground Text color fg="red"
Font Font style of the text font=("Arial", 12, "bold")
padx, pady Padding around the text padx=10, pady=5
width, height Size of the Checkbutton width=20
Position of text inside the widget
Anchor anchor="w"
(n, s, e, w, center)
Justify multiple lines of text (left, center,
Justify justify="left"
right)
Defines widget usability (NORMAL,
State state=DISABLED
DISABLED, ACTIVE)
selectcolor Color of the box when checked selectcolor="yellow"
Border style (flat, groove, raised, ridge,
Relief relief="raised"
solid, sunken)
Example 1:
import tkinter as tk
root = [Link]()
[Link]("Simple Checkbutton")
# variable to store state
var = [Link]()
cb = [Link](root, text="Accept Terms & Conditions", variable=var)
[Link](pady=10)
[Link]()
When you check the box, [Link]() will become 1.
When you uncheck it, [Link]() will become 0.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 36
Example 2:
import tkinter as tk
def show_status():
print("Python:", [Link]())
print("Java:", [Link]())
root = [Link]()
[Link]("Checkbutton Example")
# Variables to store checkbox states
var1 = [Link]()
var2 = [Link]()
cb1 = [Link](root, text="Python", variable=var1, onvalue=1, offvalue=0,
font=("Arial", 12),
fg="blue", selectcolor="lightgray", command=show_status)
[Link](pady=5)
cb2 = [Link](root, text="Java", variable=var2, onvalue=1, offvalue=0,
font=("Arial", 12),
fg="green", selectcolor="yellow", command=show_status)
[Link](pady=5)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 37
RADIO BUTTON
In tkinter, a radiobutton widget lets the user choose only one option from a set of
choices (unlike checkbutton where you can select multiple).
Syntax
rb = radiobutton(master, options...)
Common Attributes of Radiobutton
Attribute Description Example
Master Parent window or frame root
Text displayed beside the radio
Text text="Male"
Button
A Tkinter variable (IntVar, StringVar)
Variable variable=gender
that stores the selected value
Value The value assigned when that option is value="Male"
selected
Command Function called when selection command=show_choice
Changes
bg / background Background color bg="lightblue"
fg / foreground Text color fg="red"
Font Font style font=("Arial", 12, "bold")
padx, pady Padding around the text padx=10, pady=5
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 38
width, height Size of the button widget width=20
Anchor Position of text (n, s, e, w, center) anchor="w"
Justify Justify multi-line text (left, center,
justify="left"
right)
State Widget usability (NORMAL,
state=DISABLED
DISABLED, ACTIVE)
selectcolor Fill color of the circle when selected selectcolor="yellow"
Relief Border style (flat, groove, raised, ridge, solid,
relief="ridge"
sunken)
Example:
import tkinter as tk
root = [Link]()
[Link]("Simple Radiobutton")
# variable to store selected option
choice = [Link]()
[Link]("None") # default value
rb1 = [Link](root, text="Option 1", variable=choice, value="Option 1")
[Link](pady=5)
rb2 = [Link](root, text="Option 2", variable=choice, value="Option 2")
[Link](pady=5)
[Link]()
Example:
import tkinter as tk
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 39
def show_choice():
print("Selected Gender:", [Link]())
root = [Link]()
[Link]("Radiobutton Example")
# Tkinter variable
gender = [Link]()
[Link]("None") # default value
rb1 = [Link](root, text="Male", variable=gender, value="Male", font=("Arial",
12), fg="blue", command=show_choice)
[Link](pady=5)
rb2 = [Link](root, text="Female", variable=gender, value="Female",
font=("Arial", 12), fg="green", command=show_choice)
[Link](pady=5)
rb3 = [Link](root, text="Other", variable=gender, value="Other", font=("Arial",
12), fg="purple", command=show_choice)
[Link](pady=5)
[Link]()
ENTRY
The entry widget is used to create a single-line text box for user input (like username,
password, search bar).
Syntax
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 40
entry = entry(master, options...)
Common Attributes of Entry
Attribute Description Example
Master Parent window/frame root
Connects the Entry with a Tkinter variable
textvariable textvariable=name
(StringVar, IntVar)
Masks the characters (used in password
Show show="*"
fields)
Width Width of entry box (in characters) width=30
Font Font style and size font=("Arial", 12)
fg / foreground Text color fg="blue"
bg / background Background color bg="lightyellow"
bd / borderwidth Border thickness bd=5
Border style (flat, groove, ridge, sunken,
Relief relief="sunken"
raised, solid)
State State of entry (NORMAL, DISABLED, state="disabled"
readonly)
Justify Alignment of text inside the entry (left, justify="center"
center, right)
insertbackground Cursor (insertion point) color insertbackground="red"
selectbackground Background color of selected text selectbackground="yellow"
selectforeground Foreground color of selected text selectforeground="black"
Example:
import tkinter as tk
root = [Link]()
[Link]("Entry Example")
# StringVar for entry text
name = [Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 41
entry = [Link](root, textvariable=name, width=30, font=("Arial", 12),
fg="blue", bg="lightyellow", bd=3, relief="sunken")
[Link](pady=10)
[Link]()
This creates an entry box where you can type text.
If you do print([Link]()), it will return the entered text.
LISTBOX
The listbox widget is used to display a list of items from which the user can select
one or multiple options.
Syntax
listbox = listbox(master, options...)
Common Attributes of Listbox
Attribute Description Example
Master Parent window/frame root
Height Number of visible rows height=5
width Width of listbox (in characters) width=20
Selection mode:
• SINGLE → only one item
selectmode • BROWSE → (default) single item selectmode=MULTIPLE
but draggable
• MULTIPLE → multiple items
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 42
• EXTENDED → multiple with
Shift/Ctrl
bg / background Background color bg="lightyellow"
fg / foreground Text color fg="blue"
font Font style font=("Arial", 12)
bd / borderwidth Border thickness bd=3
relief Border style (flat, groove, raised,
relief="sunken"
ridge, sunken, solid)
highlightcolor Highlight border color when focused highlightcolor="red"
selectbackground Background color of selected item(s) selectbackground="lightblue"
selectforeground Text color of selected item(s) selectforeground="black"
exportselection If 0, selection remains active even when
exportselection=0
focus changes
yscrollcommand Connects vertical scrollbar yscrollcommand=[Link]
xscrollcommand Connects horizontal scrollbar xscrollcommand=[Link]
Example:
import tkinter as tk
root = [Link]()
[Link]("Listbox Example")
listbox = [Link](root, height=5, width=20, font=("Arial", 12),
selectmode=[Link], bg="lightyellow", fg="blue",
selectbackground="lightblue", bd=3, relief="sunken")
[Link](pady=10)
# Add items
items = ["Python", "Java", "C++", "JavaScript", "PHP"]
for item in items:
[Link]([Link], item)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 43
[Link]()
TEXT
The text widget in tkinter is one of the most powerful widgets because it allows
users to enter and display multi-line text (unlike entry, which is single-line).
It also supports advanced formatting, scrolling, and tagging.
SYNTAX:
text = text(parent, options)
Common Attributes of Text Widget
Attribute Description
bg Background color of the text area
fg Foreground (text) color
font Font style and size
height Height of the widget (in text lines, not pixels)
width Width of the widget (in characters, not pixels)
Controls text wrapping: "none" (no wrap, needs scrollbar),
wrap
"char" (wrap by character), "word" (wrap by word)
state "normal" (editable) or "disabled" (read-only)
insertbackground Color of the insertion cursor (caret)
selectbackground Background color of selected text
padx, pady Internal padding
yscrollcommand Connects vertical scrollbar
xscrollcommand Connects horizontal scrollbar
Common Methods
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 44
Method Description
.insert(index, text) Insert text at a given position (e.g., "1.0" means line 1, char 0)
.delete(start, end) Delete text between indices
.get(start, end) Get text between positions
.index(index) Get position of a given index
.see(index) Scrolls the text view to make index visible
.mark_set(mark, index) Set a mark (like cursor position)
.tag_add(tag, start, end) Apply a tag (style) to text
.tag_config(tag, options) Configure style of a tag
Example:
import tkinter as tk
root = [Link]()
[Link]("Text Widget Example")
# Create Text widget
text = [Link](root,
height=10,
width=40,
font=("Arial", 12),
bg="lightyellow",
fg="blue",
wrap="word")
[Link](pady=10)
# Insert some text
[Link]("1.0", "Hello! This is a Tkinter Text widget.\nYou can write multiple lines
here.")
# Add a tag for formatting
text.tag_add("highlight", "1.0", "1.5") # highlight "Hello"
text.tag_config("highlight", background="orange", foreground="white")
# Disable editing
# [Link](state="disabled")
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 45
EVENTS AND BINDINGS
• In tkinter, events are actions that occur when a user interacts with the GUI, such
as pressing a key, clicking a mouse button, or resizing a window.
• Tkinter provides a powerful mechanism to handle these events and make your
application responsive.
What is an Event?
An event is any user action or system action that occurs in the application, such as:
• Key press / key release
• Mouse click / mouse movement
• Window resize
• Focus change
WHAT IS BINDING?
• Binding means linking a specific event with a function (also called an event
handler or callback).
• When the event occurs → the bind function is executed.
• We use the .bind() method to attach an event to a widget.
Syntax
[Link]("<event>", callback_function)
• widget → tkinter widget (button, label, entry, etc.)
• <event> → event pattern in angle brackets
• callback_function → function to be executed when event occurs
(must accept an event parameter)
Event Object
When an event occurs, tkinter automatically passes an event object to the callback
function.
This object contains details such as:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 46
• event.x, event.y → mouse pointer coordinates
• [Link] → character of key pressed
• [Link] → symbolic name of key
• [Link] → widget where event occurred
Event Pattern Description
Left Mouse Click <Button-1> When left mouse button is clicked
Right Mouse Click <Button-3> Right mouse click
Double Click <Double-1> Double left click
Key Press <Key> Any key pressed
Specific Key <a> Pressing the a key
Enter Key <Return> Pressing Enter
Mouse Enter <Enter> Mouse cursor enters widget
Mouse Leave <Leave> Mouse cursor leaves widget
Focus In <FocusIn> Widget gets focus
Focus Out <FocusOut> Widget loses focus
Mouse Click Example
import tkinter as tk
def on_click(event):
print("Mouse clicked at:", event.x, event.y)
root = [Link]()
btn = [Link](root, text="Click Me")
[Link](pady=20)
[Link]("<Button-1>", on_click)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 47
Key Press Example
import tkinter as tk
def on_key(event):
print("Key pressed:", [Link], "Keysym:", [Link])
root = [Link]()
[Link]("<Key>", on_key) # Bind to root window
[Link]()
keysym (short for key symbol) represents the symbolic name of the key that was
pressed on the keyboard.
Mouse Enter / Leave Example
import tkinter as tk
def on_enter(event):
[Link](text="Mouse Inside")
def on_leave(event):
[Link](text="Mouse Outside")
root = [Link]()
label = [Link](root, text="Hover over me", width=20, height=2, bg="lightblue")
[Link](pady=20)
[Link]("<Enter>", on_enter)
[Link]("<Leave>", on_leave)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 48
Left click Right click example
import tkinter as tk
# Create main window
root = [Link]()
[Link]("Events and Bindings Example")
[Link]("300x200")
# Create a button
btn = [Link](root, text="Click Me")
[Link](pady=50)
# Bind left-click event
[Link]("<Button-1>", lambda e: print("Left click on button"))
# Bind right-click event //Here lambda e: is just a short way of writing a function
that takes the event object (commonly named e or event) as its parameter.
[Link]("<Button-3>", lambda e: print("Right click on button"))
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 49
Example:
import tkinter as tk
root = [Link]()
[Link]("Unbind Example")
[Link]("300x200")
btn = [Link](root, text="Click Me")
[Link](pady=50)
# Function for left click
def left_click(event):
print("Left Clicked!")
# Bind left click
[Link]("<Button-1>", left_click)
# Function to unbind on right click
def remove_binding(event):
[Link]("<Button-1>")
print("Left click binding removed!")
# Bind right click to remove left click binding
[Link]("<Button-3>", remove_binding)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 50
Drawing on canvas
• In tkinter, the canvas widget is designed exactly for drawing shapes, lines,
and handling graphics.
• You can draw things like rectangles, ovals, lines, text, images, etc., And also
update them dynamically.
• The canvas has two coordinate systems: the window system (left top corner
x=0,y=0) and the canvas coordinate system that defines where items are drawn.
Syntax:
c = canvas(root, height, width, bd, bg, ..)
Optional parameters:
• root = root window.
• height = height of the canvas widget.
• width = width of the canvas widget.
• bg = background colour for canvas.
• bd = border of the canvas window.
• scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom
and right.
• highlightcolor colour shown in the focus highlight.
• cursor it can be defined as a cursor for the canvas which can be a circle, a do,
an arrow etc.
• confine decides if canvas can be accessed outside the scroll region.
• relief type of the border which can be sunken, raised, groove and ridge.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 51
Some common drawing methods:
Creating a Line
SYNTAX:canvas.create_line(x1, y1, x2, y2, ..., options)
• draws a straight line between given points.
• can take multiple points → create_line(10, 10, 100, 50, 200, 100) makes a
zigzag line.
Example: canvas.create_line(50, 50, 200, 50, fill="blue", width=3)
Creating an Oval
SYNTAX: canvas.create_oval(x1, y1, x2, y2, options)
• draws an oval (or circle if width = height).
• bounding box: the oval fits inside the rectangle defined by (x1, y1, x2, y2).
Example: canvas.create_oval(250, 100, 350, 200, fill="pink", outline="red", width=2)
Creating an rectangle
Syntax:canvas.create_rectangle(x1, y1, x2, y2, options)
• draws a rectangle using two diagonal corners (x1, y1) and (x2, y2).
Example:canvas.create_rectangle(50, 100, 200, 150, fill="lightgreen",
outline="black", width=2)
Creating an arc
Syntax:canvas.create_arc(x1, y1, x2, y2, start=angle, extent=angle,
style=arc/chord/pieslice)
• draws an arc (part of an oval).
• start = starting angle in degrees (0 = east/right).
• extent = how many degrees to sweep.
• style → how the arc is drawn:
• Arc(default) → just the curved line
• chord → arc + straight line connecting ends
• pieslice → arc + lines connecting to center (like pie chart)
•
Example
• canvas.create_arc(100, 200, 200, 300, start=0, extent=150, fill="yellow",
outline="black", style="pieslice")
Line
To draw a line we use the create_line() method.
This takes a series of x and y coordinates to draw the line.
As a minimum you need to supply 2 coordinates for the start and end of the line.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 52
Example 1:
import tkinter as tk
from tkinter import Canvas
root = [Link]()
[Link]("Canvas Line Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
canvas.create_line(10, 10, 150, 50)
[Link]()
Example 2:
import tkinter as tk
root = [Link]()
[Link]("Canvas Line Example")
# Create a Canvas
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Draw a single line
canvas.create_line(50, 50, 200, 50, fill="blue", width=3)
# Draw multiple connected lines (zigzag)
canvas.create_line(50, 100, 150, 150, 250, 100, 350, 150, fill="red", width=2)
# Diagonal line
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 53
canvas.create_line(50, 200, 300, 250, fill="green", dash=(4, 2), width=3)
[Link]()
Example 3:
import tkinter as tk
root = [Link]()
[Link]("Canvas Arrow Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Simple line with arrow at the end
canvas.create_line(50, 50, 200, 50, fill="blue", width=3, arrow=[Link])
# Arrow at the start
canvas.create_line(50, 100, 200, 100, fill="green", width=3, arrow=[Link])
# Arrows at both ends
canvas.create_line(50, 150, 200, 150, fill="red", width=3, arrow=[Link])
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 54
OVAL
• The create_oval() method will create an oval, but will create a circle if given
equal coordinates.
• The oval will be drawn between the top left and bottom right coordinates.
• If the difference between the top to bottom and left to right is the same then a
circle will be drawn.
Example 1:
import tkinter as tk
from tkinter import Canvas
root = [Link]()
[Link]("Canvas Oval Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
canvas.create_oval(20, 20, 100, 100)
[Link]()
Example 2:
import tkinter as tk
root = [Link]()
[Link]("Canvas Oval Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Simple oval
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 55
canvas.create_oval(50, 50, 200, 150, outline="black", width=2)
# Filled oval
canvas.create_oval(220, 50, 370, 150, fill="lightblue", outline="blue", width=3)
# Circle (same width & height for bounding box)
canvas.create_oval(100, 180, 200, 280, fill="lightgreen", outline="darkgreen",
width=2)
[Link]()
Rectangle
The create_rectangle() method creates a rectangle shape, essentially creating any four
sided regular shape.
By default, the two coordinates given are the top left and bottom right of the rectangle
produced.
Example 1:
import tkinter as tk
from tkinter import Canvas
root = [Link]()
[Link]("Canvas Rectangle Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
canvas.create_rectangle(20, 20, 100, 100)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 56
Example 2:
import tkinter as tk
root = [Link]()
[Link]("Canvas Rectangle Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Simple rectangle
canvas.create_rectangle(50, 50, 200, 150, outline="black", width=2)
# Rectangle with fill color
canvas.create_rectangle(220, 50, 370, 150, fill="lightblue", outline="blue", width=3)
# Square (just a rectangle with equal width and height)
canvas.create_rectangle(100, 180, 200, 280, fill="lightgreen", outline="darkgreen",
width=2)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 57
Arc
• The create_arc() method will create a segment of a circle.
• This follows the same rules as the create_oval() method, but in this case the
coordinates will only draw a part of the oval of the same dimensions.
• Angles are measured in degrees, starting at 3 o’clock (east) position.
• The direction is counterclockwise.
start=0 → begins at rightmost point (3 o’clock)
extent=90 → draws 90° counterclockwise (upward)
start=180 → begins at leftmost point (9 o’clock)
extent=180 → draws half a circle
Example 1:
import tkinter as tk
from tkinter import Canvas
root = [Link]()
[Link]("Canvas Arc Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
canvas.create_arc(20, 20, 100, 100)
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 58
Example 2:
import tkinter as tk
root = [Link]()
[Link]("Canvas Arc Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Pie slice (default)
canvas.create_arc(50, 50, 200, 200, start=0, extent=90, fill="lightblue")
# Arc (only the curve)
canvas.create_arc(220, 50, 370, 200, start=0, extent=150, style="arc", outline="red",
width=3)
# Chord
canvas.create_arc(50, 150, 200, 280, start=45, extent=180, style="chord",
fill="lightgreen")
[Link]()
FULL CANVAS EXAMPLE
import tkinter as tk
root = [Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT4 REGULAR EXPRESSION AND GUI USING TKINTER 59
[Link]("Canvas Shapes Example")
canvas = [Link](root, width=400, height=300, bg="white")
[Link]()
# Line
canvas.create_line(50, 50, 200, 50, fill="blue", width=3)
# Rectangle
canvas.create_rectangle(50, 100, 200, 150, fill="lightgreen", outline="black")
# Oval
canvas.create_oval(250, 100, 350, 200, fill="pink", outline="red")
# Arc
canvas.create_arc(100, 200, 200, 300, start=0, extent=150, fill="yellow",
outline="black", style="pieslice")
[Link]()
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme