PP UT-5 Material
PP UT-5 Material
1
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
2
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
3
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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
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.
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
8
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
9
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
10
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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
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:
15
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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.
18
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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
21
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
22
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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
24
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
25
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.
Python Programming
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
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
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
38
Mr. K. Leela Prasad, Asst. Prof., CSE Dept.