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

Python Chapter5 Notes

Chapter 5 discusses Python GUI programming using Tkinter, outlining its features and how to create GUI applications. It explains the use of special methods in Python, such as __init__ and __str__, and provides examples of common widgets like buttons, labels, and entry fields. Additionally, it covers event handling, styling, and the MVC pattern for organizing code in GUI applications.

Uploaded by

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

Python Chapter5 Notes

Chapter 5 discusses Python GUI programming using Tkinter, outlining its features and how to create GUI applications. It explains the use of special methods in Python, such as __init__ and __str__, and provides examples of common widgets like buttons, labels, and entry fields. Additionally, it covers event handling, styling, and the MVC pattern for organizing code in GUI applications.

Uploaded by

JavedAhmad Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Chapter 5

Python - GUI Programming (Tkinter)

Python provides various options for developing graphical user interfaces


(GUIs). Most important are listed below.
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped
with Python.
 wxPython − This is an open-source Python interface for
wxWindows http://wxpython.org.
 JPython − JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local
machine http://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter
provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps −
 Import the Tkinter module.
 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by
the user.

Example

import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()

output:
This would create a following window −
What are Special Methods in Python?
Special methods in Python are functions that start and end with double
underscores (like __init__, __str__).
They are used inside classes to perform special operations.

__init__ method
This is called a constructor. It runs automatically when you create a new
object.
Use: To initialize values when an object is created.
Example:
class Student:
def __init__(self, name):
self.name = name

s = Student("Alice")
print(s.name) # Output: Alice
Explanation:
 When we write s = Student("Alice"), Python calls __init__ automatically.
 The name "Alice" is stored inside the object using self.name.

__str__ method
This method changes what is printed when you use print(object).
Example:
class Student:
def __init__(self, name):
self.name = name

def __str__(self):
return "Student name is: " + self.name

s = Student("John")
print(s) # Output: Student name is: John
Explanation:
 __str__ returns a string.
 Instead of showing a memory address, it shows a user-friendly message.

What is GUI?
GUI stands for: Graphical User Interface
 It is a way for users to interact with a program using buttons, textboxes,
windows, etc.
 Without GUI we type commands (Command-line interface)
 With GUI we click buttons, type in boxes, etc.
 Python uses a built-in module called Tkinter for creating GUIs.

Step-by-step:
Step 1: Import Tkinter
import tkinter as tk
We import the module to use GUI features.
Step 2: Create the main window
window = tk.Tk()
This creates a window where we’ll place our widgets (like buttons or labels).
Step 3: Add a label (to show text)
label = tk.Label(window, text="Hello!")
label.pack()
 Label is used to display text.
 pack() places it on the screen.
Step 4: Show the window
window.mainloop()
This keeps the window open. Without this, the window will close immediately.
Example:
import tkinter as tk

window = tk.Tk()
window.title("My First GUI")

label = tk.Label(window, text="Hello!")


label.pack()

window.mainloop()

What are Widgets?


Widgets are the building blocks of a GUI.
They are like LEGO blocks: You use them to build your interface.

Common Widgets:
Widget What it does
Label Shows text
Button Clickable button
Entry Single-line input field
Text Multi-line text area
Widget What it does
Listbox A list of items
Radiobutton Choose one option
Checkbutton Checkbox (yes/no)
1. Entry Example (Text input):
entry = tk.Entry(window)
entry.pack()
You use this when you want the user to type something.
2. Button Example (Click to do something):
def say_hello():
name = entry.get()
label.config(text="Hello, " + name)

button = tk.Button(window, text="Greet", command=say_hello)


button.pack()
Explanation:
 entry.get() gets the text typed by the user.
 label.config() changes the label's text.

3. Styling Your GUI (Changing colors and fonts)


You can change the look of your widgets using options like:
Option What it changes
fg Text color
bg Background color
font Font type and size
Example:
label = tk.Label(window, text="Welcome", fg="blue", bg="yellow",
font=("Arial", 16, "bold"))
label.pack()
4. Event Handling (What happens when user clicks)
When the user does something (like click a button), an event occurs.
We use a function (called a callback) to respond.
Example:
def greet():
print("Button clicked!")

btn = tk.Button(window, text="Click Me", command=greet)


btn.pack()
Explanation:
 When the user clicks the button, the greet() function runs.

 MVC Pattern (Model-View-Controller)


MVC is a way to organize your code into 3 parts:
Part features
Model Stores the data
View Shows the GUI to the user
Controller Connects user actions to the model and view

Example:
class UserData: # Model
def __init__(self):
self.name = ""

def update_label(): # Controller


data.name = entry.get()
label.config(text="Hello " + data.name)

data = UserData()
entry = tk.Entry(window) # View
entry.pack()

button = tk.Button(window, text="Say Hello", command=update_label)


button.pack()

label = tk.Label(window, text="")


label.pack()

 Object-Oriented GUI (Using Classes)


Using classes makes your GUI program:
 Easier to read
 More organized
 Reusable
Example:
class MyApp:
def __init__(self, root):
self.root = root
self.root.title("OOP GUI")

self.entry = tk.Entry(root)
self.entry.pack()

self.button = tk.Button(root, text="Click", command=self.say_hello)


self.button.pack()

self.label = tk.Label(root, text="")


self.label.pack()

def say_hello(self):
name = self.entry.get()
self.label.config(text="Hello, " + name)

root = tk.Tk()
app = MyApp(root)
root.mainloop()
Explanation:
 Everything is inside a class.
 GUI elements (entry, button, label) are part of the class.
 The function say_hello() is also inside the class.

 How to Keep GUI Code Clean (No Mess!)


To write good GUI programs:
Do’s:
 Use classes to group related code
 Create functions for actions (like button clicks)
 Follow MVC structure
 Use clear names like submit_button, name_entry
Dont’s:
Don’t write everything in one place
 Don’t use confusing variable names like a, x, y
 Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in
a GUI application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as
well as a brief description in the following table −

Sr.No. Operator & Description

1 Button
The Button widget is used to display buttons in your application.

2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.

3 Checkbutton
The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.

4 Entry
The Entry widget is used to display a single-line text field for
accepting values from a user.

5 Frame
The Frame widget is used as a container widget to organize other
widgets.

6 Label
The Label widget is used to provide a single-line caption for other
widgets. It can also contain images.

7 Listbox
The Listbox widget is used to provide a list of options to a user.

8 Menubutton
The Menubutton widget is used to display menus in your application.

9 Menu
The Menu widget is used to provide various commands to a user.
These commands are contained inside Menubutton.

10 Message
The Message widget is used to display multiline text fields for
accepting values from a user.

11 Radiobutton
The Radiobutton widget is used to display a number of options as
radio buttons. The user can select only one option at a time.

12 Scale
The Scale widget is used to provide a slider widget.

13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various
widgets, such as list boxes.

14 Text
The Text widget is used to display text in multiple lines.

15 Toplevel
The Toplevel widget is used to provide a separate window container.

16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget,
which can be used to select from a fixed number of values.

17 PanedWindow
A PanedWindow is a container widget that may contain any number
of panes, arranged horizontally or vertically.

18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to
act as a spacer or container for complex window layouts.

19 tkMessageBox
This module is used to display message boxes in your applications.

Python - Tkinter Button

Syntax
simple syntax to create this widget −
w = Button ( master, option=value, ... )
Parameters
 master − This represents the parent window.
 options − Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.

Example
import Tkinter
import tkMessageBox

top = Tkinter.Tk()

def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
top.mainloop()

OUTPUT:
When the above code is executed, it produces the following result −
Python - Tkinter Checkbutton
Syntax
simple syntax to create this widget −
w = Checkbutton ( master, option, ... )
Example
from Tkinter import *
import tkMessageBox
import Tkinter

top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Python - Tkinter Entry
Syntax
Here is the simple syntax to create this widget −
w = Entry( master, option, ... )
Parameters
 master − This represents the parent window.
 options − Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Example
Try the following example yourself −
from Tkinter import *

top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)

top.mainloop()
When the above code is executed, it produces the following result −

Python - Tkinter Label


Syntax
Here is the simple syntax to create this widget −
w = Label ( master, option, ... )
Example
Try the following example yourself −
from Tkinter import *

root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )

var.set("Hey!? How are you doing?")


label.pack()
root.mainloop()
When the above code is executed, it produces the following result −

Python - Tkinter Listbox


Syntax
Here is the simple syntax to create this widget −
Example
Try the following example yourself −
from Tkinter import *
import tkMessageBox
import Tkinter

top = Tk()

Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Python - Tkinter Message

Example
Try the following example yourself −
from Tkinter import *

root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )

var.set("Hey!? How are you doing?")


label.pack()
root.mainloop()
When the above code is executed, it produces the following result −

Python - Tkinter Radiobutton


Example
Try the following example yourself −
from Tkinter import *

def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)

root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )

R2 = Radiobutton(root, text="Option 2", variable=var, value=2,


command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var, value=3,
command=sel)
R3.pack( anchor = W)

label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result −

(Imp) Python - Tkinter tkMessageBox


Syntax
Here is the simple syntax to create this widget −
tkMessageBox.FunctionName(title, message [, options])

Parameters
 FunctionName − This is the name of the appropriate message box
function.
 title − This is the text to be displayed in the title bar of a message box.
 message − This is the text to be displayed as a message.
 options − options are alternative choices that you may use to tailor a
standard message box. Some of the options that you can use are default
and parent. The default option is used to specify the default button, such
as ABORT, RETRY, or IGNORE in the message box. The parent option
is used to specify the window on top of which the message box is to be
displayed.
You could use one of the following functions with dialogue box −
 showinfo()
 showwarning()
 showerror ()
 askquestion()
 askokcancel()
 askyesno ()
 askretrycancel ()

Example:

from tkinter import *


from tkinter import messagebox
root = Tk()
root.geometry("300x200")
w = Label(root, text ='GeeksForGeeks', font = "50")
w.pack()
messagebox.showinfo("showinfo", "Information")
messagebox.showwarning("showwarning", "Warning")
messagebox.showerror("showerror", "Error")
messagebox.askquestion("askquestion", "Are you sure?")
messagebox.askokcancel("askokcancel", "Want to continue?")
messagebox.askyesno("askyesno", "Find the value?")
messagebox.askretrycancel("askretrycancel", "Try again?")
root.mainloop()
Output:

You might also like