Python Chapter5 Notes
Python Chapter5 Notes
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")
window.mainloop()
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)
Example:
class UserData: # Model
def __init__(self):
self.name = ""
data = UserData()
entry = tk.Entry(window) # View
entry.pack()
self.entry = tk.Entry(root)
self.entry.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.
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.
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.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 −
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
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 )
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 )
label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result −
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: