0% found this document useful (0 votes)
3 views38 pages

PP UT-5 Material

The document provides an overview of Tkinter, Python's standard GUI toolkit, covering key concepts such as event-driven programming, various widgets (like Label, Entry, Button, Checkbutton, and Radiobutton), and geometry management methods (pack, grid, place). It explains the differences between terminal-based and GUI-based programs, emphasizing the responsiveness and user interaction of GUIs. Additionally, it outlines steps for creating simple GUI applications and handling user events effectively.

Uploaded by

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

PP UT-5 Material

The document provides an overview of Tkinter, Python's standard GUI toolkit, covering key concepts such as event-driven programming, various widgets (like Label, Entry, Button, Checkbutton, and Radiobutton), and geometry management methods (pack, grid, place). It explains the differences between terminal-based and GUI-based programs, emphasizing the responsiveness and user interaction of GUIs. Additionally, it outlines steps for creating simple GUI applications and handling user events effectively.

Uploaded by

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

Python Programming

UNIT-5 (Tkinter GUI, Event Driven Programming, Widgets)


The Behavior of Terminal-Based Programs and GUI-Based Programs, Label, Entry and
Button widget; Tkinter Geometry methods (pack(), grid(), place()); Event-Driven
Programming, Command Buttons and Responding to Events; CheckButton and
Radiobutton widgets;
Menu and Menu button widgets; Listbox and Scrollbar widgets; Messagebox and Toplevel
widget; File Dialog widget;

5.0 Differences Between Terminal-Based Programs and GUI-Based


Programs:
Aspect Terminal-Based Programs GUI-Based Programs
Sequential, runs line by line Event-driven, waits for user actions
Execution Flow
until completion. (clicks, typing, resizing).
Text-based input/output via Interaction through graphical elements
User
keyboard. Program often (buttons, menus, text boxes). Multiple
Interaction
blocks until input is given. actions can happen simultaneously.
Limited; program pauses at Highly responsive; GUI remains active
Responsiveness
input() until user responds. and reacts instantly to events.
Output is plain text messages Feedback is visual (pop-ups,
Feedback
or error codes. highlighted fields, progress bars).
Error Errors shown as text Errors can be displayed as dialog boxes
Handling tracebacks in console. or highlighted widgets for clarity.
Resource Lightweight, minimal Heavier, requires more resources for
Usage CPU/memory usage. rendering graphics and handling events.
Linear, text-driven, minimal Flexible layouts, colors, fonts, images,
Design Style
customization. and interactive widgets.
Steeper for non-technical users
Learning Easier for beginners; intuitive with
(requires command
Curve visual cues.
knowledge).
Automation scripts, developer Desktop apps, educational tools, games,
Use Cases
tools, server-side tasks. data-entry systems.
Tkinter apps, PyQt dashboards,
Examples Git, SSH, Python CLI scripts.
browsers, games.

1
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.0.1 Introduction to GUI:


A GUI (Graphical User Interface) allows users to interact with electronic devices using
graphical icons and visual indicators, rather than text-based interfaces, typewritten command
labels, or text navigation. Tkinter is Python's standard GUI (Graphical User Interface) package.
It is a thin object-oriented layer on top of Tcl/Tk.
Tkinter is a combination of “Tk” and “inter”, where Tk stands for Tool kit and inter stands for
interface i.e., Tkinter is a python interface to the Tk tool kit.
A popular GUI Tool kit that was originally developed for Tcl programming language. Tk
provides a rich collection of widgets for building interactive applications.
Widget Purpose Example Use
Showing instructions like “Enter your
Label Displays text or images
name”
Button Executes a function when clicked “Submit” or “Exit” buttons
Entry Single-line text input Username or password fields
Text Multi-line text input Notes or comments box
Checkbutton Toggle option (on/off) “Remember me” checkbox
Radiobutton Select one option from a group Choosing gender (Male/Female)
Listbox Displays a list of items Selecting from a list of courses
Frame Container for grouping widgets Organizing layout sections
Drawing shapes, images, or custom
Canvas Creating charts or diagrams
graphics

5.0.2 Tkinter's Role in GUI Development


Tkinter is Python's standard library for creating GUI-based programs. It provides a toolkit for
building graphical interfaces with minimal effort. Here's how it facilitates GUI development:
• Ease of Use: Tkinter's simple syntax allows developers—even beginners—to create
windows, menus, and widgets like buttons and entry fields quickly.
• Widget Variety: It offers a wide range of widgets to design diverse interfaces, such as
labels, text boxes, frames, canvases, progress bars, and more.
• Event Handling: Tkinter includes mechanisms to handle user actions (events), such as
button clicks or text input, enabling dynamic and interactive programs.
• Cross-Platform Compatibility: Since Tkinter is part of Python's standard library, it
works seamlessly across different operating systems.
• Customization: Developers can enhance the aesthetics by modifying widget
properties, setting colors, fonts, layouts, etc.

5.0.3 Steps to create a simple GUI application using Tkinter:


1. import tkinter module
2. Create the main application window
3. Add the widgets like labels, buttons, frames etc., to the window.
4. Call the main event loop so that the actions can take place on the user’s computer
screen.

2
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.0.3 Simple GUI Creation with Methods title() and geometry():


Tkinter provides a Tk class to create a window. The title() method sets the title of the window,
and geometry() sets the size and placement of the window.
Example:

3
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.1 Program on Label Creation:


A Label widget is used to display text or images. You can customize various options such as
text, font, background color (bg), and foreground color (fg).
Example:

The pack() method is one of the three geometry managers in Tkinter (the other two being grid()
and place()). It organizes widgets in blocks before placing them in the parent widget.
Default Behavior: By default, pack() will add the widget to the window from top to bottom,
centering it horizontally.
The [Link]() is a method in Tkinter that is used to run the main loop of your application.
It's an essential part of any Tkinter-based GUI application.
• Main Loop: The main loop is a continuous loop that runs in the background of your
application. It waits for events (such as button clicks, key presses, mouse movements,
etc.) and dispatches them to the appropriate event handlers.
• Blocking Call: [Link]() is a blocking call, which means it will run indefinitely
until the main window is closed. This keeps your application responsive and able to
react to user input.

4
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.2 Program on Entry Creation:


An Entry widget is used to accept a single line of text input from the user. You can customize
text color (fg), background color (bg), width, font, and use methods like get(), delete(), and
insert().
Program:

Explanation:
The statement from tkinter import Tk, Entry, Button is an import statement in Python that
allows you to access specific classes from the Tkinter module. Let's break it down:
• from tkinter import: This part tells Python to import specific items from the Tkinter
module.

5
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

• Tk: This is the Tk class from the Tkinter module. It is used to create the main window
of your application. When you create an instance of the Tk class, it initializes the
Tkinter application and creates the main window.
• Entry: This is the Entry class from the Tkinter module. It is used to create a single-line
text entry field within the Tkinter window. Entry widgets are commonly used to take
input from the user.
• Button: This is the Button class from the Tkinter module. It is used to create clickable
buttons within the Tkinter window. Buttons can be configured to perform specific
actions when clicked.

5.3 Program on Button Creation:


A Button widget is used to execute a command when clicked. You can customize the text,
font, background color (bg), foreground color (fg), active background color
(activebackground), and active foreground color (activeforeground).
Program:

6
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Explanation: The statement from tkinter import Tk, Label, Button is a Python import
statement that allows you to access specific classes from the Tkinter module.
• from tkinter import: This part of the statement tells Python to import specific items
from the Tkinter module.
• Tk: This is the Tk class from the Tkinter module. It is used to create the main window
of your application. When you create an instance of the Tk class, it initializes the
Tkinter application and creates the main window.
• Label: This is the Label class from the Tkinter module. It is used to create text or image
labels within the Tkinter window. Labels are often used to display static text or images.
• Button: This is the Button class from the Tkinter module. It is used to create clickable
buttons within the Tkinter window. Buttons can be configured to perform specific
actions when clicked.

7
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.4 Introduction to Tkinter Geometry Methods:


Tkinter provides three geometry managers to organize widgets within a parent widget:
1. pack(): Arranges widgets in blocks, filling the available space.
2. grid(): Organizes widgets in a table-like structure with rows and columns.
3. place(): Allows precise positioning of widgets using coordinates.

5.4.1 Program on pack() with Options:


The pack() method can be customized using various options:
• expand: If set to True, the widget expands to fill any extra space.
• side: Specifies which side of the parent widget to pack against (TOP, BOTTOM, LEFT,
RIGHT).
• fill: Determines if the widget should expand to fill extra space (NONE, X, Y, BOTH).
• ipadx, ipady: Adds internal padding inside the widget (horizontal and vertical).
• padx, pady: Adds external padding outside the widget (horizontal and vertical).
Program:

8
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.4.2 Program on grid() with Options:


The grid() method organizes widgets in a table-like structure with rows and columns.
• row, column: Specifies the row and column position of the widget.
• rowspan, columnspan: Determines how many rows or columns the widget should
span.
• sticky: Aligns the widget within its grid cell (e.g., N, S, E, W).
• padx, pady: Adds padding outside the widget (horizontal and vertical).
• ipadx, ipady: Adds internal padding inside the widget (horizontal and vertical).

9
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.4.3 Program on place() with Options:


The place() method allows you to position widgets at an exact location using coordinates.
• x, y: Specifies the position of the widget using absolute coordinates.
• width, height: Defines the width and height of the widget.
Program:

10
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.5 Introduction to Event-Driven Programming:


Event-driven programming is a programming paradigm in which the flow of the program is
determined by events—such as user actions (mouse clicks, key presses), sensor outputs, or
messages from other programs. It is widely used in graphical user interfaces (GUIs) and
applications that need to respond to user inputs.
Programs on Button with Command Option and Button States
We'll use the Tkinter library, which is the standard Python interface to the Tk GUI toolkit, to
illustrate event-driven programming with buttons and their states.
Step-by-Step Guide with Examples:
1. Setting Up Tkinter: First, you need to install the Tkinter library if it is not already
installed. It usually comes pre-installed with Python.
2. Creating a Simple Window with a Button: Let's start by creating a simple window
with a button that responds to clicks.
Example:

3. Adding Command Option to Buttons: The command option in Tkinter's Button


widget allows you to specify a function to be called when the button is clicked. In the
example above, on_button_click is called when the button is clicked.

11
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Handling Button States: Buttons in Tkinter can have different states, such as normal, active,
or disabled. You can change the state of a button programmatically.
Example:

In this example, clicking the button toggles its state between enabled and disabled.

12
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5. Responding to Various Events: Tkinter allows you to bind different events to widgets.
You can use the bind method to respond to events like key presses, mouse movements,
etc.
Example:

13
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.6 Introduction to Checkbutton and Radiobutton:


1. Checkbutton:
• A Checkbutton is a widget that allows the user to select or deselect a particular option.
You can have multiple Checkbuttons, and each can be selected independently.
• Use cases include toggling settings, selecting multiple items from a list, etc.
Checkbutton Options:
• text: The text to be displayed on the Checkbutton.
• command: A function to be called when the Checkbutton is toggled.
• variable: A control variable (usually [Link]) that holds the state of the Checkbutton
(1 if selected, 0 if not).
• onvalue: The value to set the variable when the Checkbutton is selected.
• offvalue: The value to set the variable when the Checkbutton is deselected.
• get() method: Retrieves the current value of the variable.
Program with Checkbuttons demonstrating these options:

In the above example:


• Two Checkbuttons are created with text, variable, onvalue, and offvalue options.
• The on_checkbutton_toggle function prints the state of both Checkbuttons whenever
they are toggled.
• The get() method of the control variables (var1 and var2) is used to retrieve their current
values.

14
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

2. Radiobutton:
• A Radiobutton is a widget that allows the user to select one option from a set of
mutually exclusive options. Selecting a Radiobutton deselects any other Radiobutton in
the same group.
• Use cases include selecting a single option from a list of choices, such as gender
selection, quiz options, etc.
Radiobutton Options:
• text: The text to be displayed on the Radiobutton.
• variable: A control variable (usually [Link]) that holds the state of the selected
Radiobutton.
• value: The value to set the variable when the Radiobutton is selected.
• command: A function to be called when the Radiobutton is selected.
• get() method: Retrieves the current value of the variable.
Program with Radiobuttons demonstrating these options:

In the above example:


• Three Radiobuttons are created with text, variable, value, and command options.
• The on_radiobutton_select function prints the currently selected option whenever a
Radiobutton is selected.
• The get() method of the control variable (var) is used to retrieve the current value.

15
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.7 Introduction to Menu and Menubutton widgets:


1. Menu:
• A Menu in Tkinter is a dropdown list of options or commands that a user can select. It
is typically found in a menu bar at the top of a window.
• Menus are used to organize commands and functions in an application, making them
easily accessible to the user.
Program on Menu Creation:

Explanation:
• [Link]() is a constructor of the Menu class that initializes a new menu object.
• The methods of this Menu object, such as add_command(), add_cascade(), or
add_separator(), are used to add items or submenus to the menu.
• So, while Menu is a class, the functions you call to interact with it (like add_command)
are methods of the Menu class.

16
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Methods:
• add_command(): Adds a menu item that triggers a command.
• add_cascade(): Adds a submenu to the menu.
• add_separator(): Adds a separator line to the menu.
command parameter:
• The command parameter in Tkinter's Button widget is used to specify a function
(callback) that should be executed when the button is clicked. This makes it a crucial
part of event-driven programming in Tkinter. Instead of binding events manually, the
command parameter allows you to directly associate a button with a specific function
that performs a desired action.
Summary:
• A menu bar is created using [Link]().
• A "File" menu is created and populated with items using add_command(),
add_separator(), and add_cascade().
• The hello and goodbye functions are triggered when the corresponding menu items are
selected.
• The menu bar is added to the window using [Link](menu=menu_bar).

17
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

2. Menubutton:
• A Menubutton is a widget that displays a menu when clicked. It is similar to a standard
button but is designed to show a dropdown menu.
• Menubuttons can be used to create context menus or standalone menus within a Tkinter
application.
Program to demonstrate on Menubutton with a Checkbutton:
Method: add_checkbutton(): Adds a checkbutton to the menu.

In the above example:


• A Menubutton is created using [Link]().
• A menu is associated with the Menubutton using [Link].
• A checkbutton is added to the menu using add_checkbutton(), and it toggles the var
variable when clicked.
• The toggle_option function prints the state of the checkbutton whenever it is toggled.

18
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.8 Introduction to Listbox and Scrollbar Widgets:


1. Listbox:
A Listbox widget displays a list of items from which a user can select one or more items. It is
useful for showing lists of data, such as file names, options, etc.
Example:

19
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Methods:
• insert(): Adds items to the Listbox.
• bind(): Attaches event handlers to Listbox events.
• get(): Retrieves items from the Listbox.
In the above example:
• The insert() method adds items to the Listbox.
• The bind() method attaches the on_select function to the <<ListboxSelect>> event.
• The get() method retrieves the selected item from the Listbox.
2. Scrollbar:
A Scrollbar widget provides a vertical or horizontal scroll bar for various widgets, such as
Listbox, Text, Canvas, etc. It is used to navigate through a list of items or large data sets.
Program on Scrollbar Widget:
Options:
• yscrollcommand: Links the Scrollbar to the vertical scrolling of another widget, such
as a Listbox.
• command: Links the Scrollbar to a command that will be called when the Scrollbar is
moved.
Example:

20
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

In the above example:


• The command option of the Scrollbar is set to [Link], linking the Scrollbar to
the vertical scrolling of the Listbox.
• The yscrollcommand option of the Listbox is set to [Link], linking the Listbox to
the Scrollbar.
5.8.3 Link a Listbox with a Scrollbar Widget:
Combining the Listbox and Scrollbar Widget, we can create a Listbox with a linked Scrollbar.

21
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

In the above combined example:


• The Listbox and Scrollbar are linked to provide a scrollable list of items.
• The on_select function prints the selected item when an item is selected from the
Listbox.

22
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.9 Introduction to messagebox and Toplevel Widgets:


1. messagebox:
• The messagebox module in Tkinter provides simple pop-up dialogs that display
messages to the user. It includes various types of message boxes like information,
warning, and error messages.
• These dialogs are commonly used to alert the user or provide information.
Program on messagebox Widget:

Methods:
• showinfo(): Displays an informational message box.
• showwarning(): Displays a warning message box.
• showerror(): Displays an error message box.

23
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

In the above example:


• show_info(), show_warning(), and show_error() functions display informational,
warning, and error message boxes respectively.
• Buttons are created to trigger these functions, and they display corresponding message
boxes when clicked.
2. Toplevel:
• The Toplevel widget in Tkinter creates a new top-level window. It is used to create
additional windows apart from the main application window.
• It can be used to create dialog boxes, popup windows, and other secondary windows.
Program on Toplevel:

In the above example:


• The open_new_window() function creates a new top-level window using the Toplevel
widget.
• A label is added to the new window to display some text.
• A button in the main window triggers the open_new_window() function, opening the
new window.

24
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.10 filedialog widget:


The filedialog widget in Tkinter is a module provides pre-built widgets that allow users to
interact with the file system for actions like:
• Selecting files to open.
• Specifying file paths to save files.
• Navigating directories.
Key Features of the filedialog Module:
• File Selection: Helps users browse and select files for opening or saving.
• Cross-Platform: Offers dialogs that match the appearance and behavior of the host
operating system.
• Customizable Options: Allows developers to configure filters for file types, default
directory locations, and titles.
Filedialog widget Functions:
1. askopenfile(): Opens a dialog to select a file and returns a file object (opened in read
mode by default).
2. askopenfiles(): Opens a dialog to allows the selection of multiple files and returns a
list of file objects.
3. askopenfilename(): Opens a dialog for selecting a file to open. Returns the selected
file's path.
4. askopenfilenames(): Opens a dialog to allows the selection of multiple files and returns
a tuple of file paths.
5. askdirectory(): Opens a dialog for selecting a directory. Returns the selected
directory's path.
6. asksaveasfile(): Opens a "Save As" dialog, and allows the user to save data into a new
file and returns a file object.
7. asksaveasfilename(): Opens a dialog for selecting a file to save. Returns the selected
file's path.

25
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5.10.1 filedialog methods:


1. askopenfile()
Allows users to select a file and returns a file object (opened in read mode by default).

Explanation to the above program:


Import Statements:
1. import tkinter as tk This imports the tkinter library, which is Python's standard GUI
(Graphical User Interface) toolkit. The alias tk is used to shorten the reference to the
module.
2. from tkinter import filedialog This imports the filedialog module from tkinter.
filedialog provides functions for creating file dialog boxes, such as opening or saving
files.

26
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Function Definition:
3. Function to select a file and display its content A comment explaining what the
upcoming function does.
4. def open_file(): This defines a function named open_file. This function allows the user
to select a file and displays its content.
5. file = [Link](mode="r", filetypes=[("Text Files", "*.txt"), ("All Files",
"*.*")])
o [Link]: Opens a dialog box for the user to select a file.
o mode="r": Opens the selected file in read mode ("r").
o filetypes = [("Text Files", "*.txt"), ("All Files", "*.*")]: Filters the types of files
shown in the dialog box.
▪ "Text Files", "*.txt": Only files with the .txt extension are displayed.
▪ "All Files", "*.*": Displays all types of files. The function returns a file
object, which is assigned to the variable file. If the user cancels the
operation, file will be None.
6. if file: This checks if the user selected a file (i.e., file is not None).
7. print(f"File Name: {[Link]}") Prints the name of the selected file using [Link].
8. content = [Link]() Reads the entire content of the file and assigns it to the variable
content.
9. print(f"Content: {content}") Prints the content of the file to the console.
10. [Link]() Closes the file to free up system resources.
Create and Configure the Tkinter Window:
11. root = [Link]() Creates the main Tkinter window and assigns it to the variable root.
12. [Link]() Hides the main Tkinter window so that it doesn't appear on the
screen. This is done because the program only needs to display the file dialog box, not
the main window.
Function Call:
13. open_file() Calls the open_file function to execute the file selection and content
display process.

27
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

2. askopenfiles()
Allows the selection of multiple files and returns a list of file objects.

Explanation:
Function Definition:
1. def open_multiple_files(): This defines a function named open_multiple_files. The
purpose of this function is to allow the user to select multiple files and print their names.
File Dialog and File Selection:
2. files = [Link](filetypes=[("Python Files", "*.py"), ("All Files", "*.*")])
o [Link]: Opens a file dialog box that allows the user to select
multiple files. It returns a list of file objects corresponding to the selected files.
o filetypes=[("Python Files", "*.py"), ("All Files", "*.*")]: Filters the types of
files shown in the dialog box.
▪ "Python Files", "*.py": Only files with the .py extension (Python files)
are shown.
▪ "All Files", "*.*": Displays all files irrespective of their extensions.
Iterating Through Selected Files:
3. for file in files: This creates a loop to iterate over each file object in the files list.

28
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

4. print(f"File Name: {[Link]}")


o Prints the name of each selected file using the [Link] attribute.
o f"File Name: {[Link]}": A formatted string (f-string) that dynamically inserts
the file name into the output.
5. [Link]() Closes each file after its name has been printed. This is important for freeing
up system resources associated with the file object.
Calling the Function:
6. open_multiple_files() This calls the open_multiple_files function to execute the process
of selecting and displaying multiple files.

29
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

3. askopenfilename()
Returns the file path (string) of a selected file.

Explanation:
Function Definition:
1. def get_file_path(): This defines a function named get_file_path. Its purpose is to open
a dialog box for file selection and display the file path of the selected file.
File Dialog and File Path Selection:
2. file_path = [Link](filetypes=[("Image Files",
"*.png;*.jpg;*.jpeg"), ("All Files", "*.*")])
o [Link]: Opens a file selection dialog box that allows the
user to choose a single file.
o filetypes=[("Image Files", "*.png;*.jpg;*.jpeg"), ("All Files", "*.*")]: Filters
the files displayed in the dialog box:
▪ "Image Files", "*.png;*.jpg;*.jpeg": Shows only image files with .png,
.jpg, or .jpeg extensions.
▪ "All Files", "*.*": Displays all types of files, regardless of their
extensions.
o The file path of the selected file is returned as a string and stored in the variable
file_path. If the user cancels the operation, file_path will be an empty string.
Print the Selected File Path:

30
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

3. print(f"Selected File Path: {file_path}")


o Prints the file path of the selected file using an f-string (formatted string).
o If no file is selected, the printed message will show an empty string as the file
path.
Calling the Function:
4. get_file_path() Calls the get_file_path function to execute the process of opening the
file dialog and displaying the selected file's path.

31
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

4. askopenfilenames()
Allows the selection of multiple files and returns a tuple of file paths.

32
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

5. askdirectory()
This function opens a directory selection dialog and returns the selected directory's path.

33
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

6. asksaveasfile()
This function opens a "Save As" dialog, and allows the user to save data into a new file and
returns a file object.

7. asksaveasfilename()
This function is similar to asksaveasfile(), but it only returns the file path as a string, without
opening or creating the file.

34
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Appendix
What is Event-Driven Programming?
Event-driven programming is a programming paradigm where the flow of the program is
determined by events, such as user actions (clicks, keypresses, etc.), messages, or changes in
the system's state. In this approach, the program remains idle, waiting for an event to occur.
When an event happens, the corresponding code (often referred to as a "callback" or "event
handler") is executed to respond to it.
This paradigm is particularly useful for creating interactive applications, where user
interactions drive the application's behavior.
Significance of Event-Driven Programming in GUI-Based Applications
In graphical user interface (GUI) applications, event-driven programming is crucial for creating
a responsive and interactive user experience. Here’s why:
• User Interaction: GUI applications rely on user input such as button clicks, mouse
movements, and text input. Event-driven programming enables the application to
respond dynamically to these actions.
• Asynchronous Execution: It allows the application to handle multiple events
concurrently, ensuring that the GUI remains responsive even when performing
background tasks.
• Scalability: Complex applications with multiple interactive elements can be managed
efficiently by associating specific event handlers with corresponding events.
• Decoupling: Logic and interface components are separated, as event handlers focus on
specific tasks. This improves code organization and maintainability.
▪ For example, in a word processing application, pressing a key triggers an event
that inserts the character into the document. Similarly, clicking the "Save"
button triggers an event to save the file.
How Tkinter Uses Event-Driven Principles
Tkinter, Python's standard GUI library, is built around the event-driven programming model.
The Tkinter mainloop continuously monitors for events and dispatches them to the appropriate
event handlers.
1. Main Event Loop:
• The mainloop() function initiates the event-driven mechanism. It keeps the application
running, waiting for events (e.g., clicks, keypresses, window resizing) and dispatching
them when they occur.
2. Callback Functions:
• Widgets like Buttons, Entries, or Menus in Tkinter use callback functions to handle
specific events. For instance, a Button widget can have a command parameter that
specifies a function to be called when the button is clicked.

35
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

3. Event Binding:
• Tkinter allows fine-grained control over events through the .bind() method. This lets
developers explicitly associate specific events (e.g., <Button-1> for left mouse clicks
or <KeyPress> for keypresses) with corresponding handlers.

36
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Assignment Questions
Tkinter GUI and Event-Driven Programming
1. Explain the differences between terminal-based programs and GUI-based programs in
terms of user interaction and application design. How does Tkinter facilitate GUI
development in Python?
2. What is event-driven programming? Discuss its significance in GUI-based applications
and explain how Tkinter uses event-driven principles to manage user interactions.
Tkinter Widgets: Label, Entry, Button
3. Discuss the purposes of Label, Entry, and Button widgets in Tkinter. Provide examples
to illustrate how each of these widgets is created and used in a Tkinter application.
4. Explain the use of the command parameter in Tkinter Button widgets. How can it be
used to trigger functions in response to user actions? Provide a practical example.
Tkinter Geometry Methods: pack(), grid(), place()
5. Compare and contrast the pack(), grid(), and place() geometry management methods in
Tkinter. When should each method be used, and what are their advantages and
limitations?
6. Design a Tkinter application with a layout that demonstrates the combined use of
pack(), grid(), and place(). Explain the rationale for your chosen layout.
Command Buttons and Event Handling
7. What are command buttons in Tkinter, and how do they interact with events? Discuss
the use of callback functions to handle button clicks in a Tkinter application.
8. Explain the process of binding events to widgets in Tkinter. How does the .bind()
method differ from the command parameter? Provide an example to illustrate your
explanation.
CheckButton and Radiobutton Widgets
9. Explain the functionality of CheckButton and Radiobutton widgets in Tkinter. How are
they different, and what are their typical use cases?
10. Discuss how you can group Radiobuttons in Tkinter to ensure that only one option is
selected at a time. Illustrate with an example.
Menu and MenuButton Widgets
11. Describe how menus and menubuttons are created in a Tkinter application. What are
their purposes, and how can they enhance user experience? Provide a use case.
12. Explain the concept of cascading menus in Tkinter. How can you implement a multi-
level menu using the Menu widget?

37
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming

Listbox and Scrollbar Widgets


13. How are Listbox and Scrollbar widgets used together in Tkinter? Write a Python
program that demonstrates a scrollable list of items using these widgets.
14. Discuss how the yscrollcommand and xscrollcommand parameters work in conjunction
with Scrollbar widgets to provide scrolling functionality in Tkinter applications.
MessageBox and Toplevel Widgets
15. What is the role of the MessageBox widget in Tkinter applications? How can it be used
to display alerts, confirmations, or information to users? Provide an example of its
usage.
16. Explain the purpose of the Toplevel widget in Tkinter. Discuss how it differs from the
main application window and how it can be utilized to create dialogs or additional
windows.
File Dialog Widget
17. What is the purpose of the File Dialog widget in Tkinter? Illustrate how to use
askopenfilename and asksaveasfilename methods to allow users to select files in a GUI
application.
18. Create a Tkinter application that utilizes a File Dialog widget to load and display the
contents of a text file. Explain the steps involved in implementing this functionality.

38
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.

You might also like