0% found this document useful (0 votes)
5 views

IIJSD 2 Advanced Python Short Notes

This document provides an overview of advanced Python programming, focusing on creating Graphical User Interfaces (GUIs) using Tkinter. It details various widgets such as buttons, labels, entry fields, and listboxes, along with their properties and methods for handling user input. Additionally, it covers file operations in Python, including opening, reading, writing, and closing files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

IIJSD 2 Advanced Python Short Notes

This document provides an overview of advanced Python programming, focusing on creating Graphical User Interfaces (GUIs) using Tkinter. It details various widgets such as buttons, labels, entry fields, and listboxes, along with their properties and methods for handling user input. Additionally, it covers file operations in Python, including opening, reading, writing, and closing files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

UNIT 2 - ADVANCED PYTHON PROGRAMMING b=Button(window, text=”click”)

GUI or Graphical User Interface? Properties of Button Widget are


 It is a user centered design to accept input from user in 1) fg - foreground color
friendly way 2) bg - background colour(label colour)
 Graphical icons like buttons, scroll bars, windows, menus, 3) width- width
text boxes are used to read inputs 4) height- height
Examples of Python Libraries to make GUIs are : ❖ ‘click event handling of button’ (using the argument
Tkinter, Flexx, Pyside, Kivi, Pyforms, PyGUI, CEFPython ‘command’ )
❖ ‘command’ is associated with a function.
What is Tkinter?
A module in the Python standard library which serves as an
interface to Tk(ToolKit). Eg:-
Widgets: from tkinter import *
Tkinter provides GUI elements which we can use to build from tkinter import messagebox
interface – such as buttons, menus and various kinds of def test( ):
entry fields and display areas. messagebox.showinfo( “Title”,“Button clicked”)
 Import the Tkinter module
window=Tk()
 Create the GUI application main window.
b=Button(window, text=“click” ,command=test)
 Add widgets to the GUI application.
b.pack()
 Enter the main event loop to take action against each event
window.mainloop()
triggered by the user Note:
b=Button(window, text=”click” ,command=window.destroy)
How to import Tkinter module to python?
from tkinter import * This enables to exit window
- added in the beginning of python program 4) Entry Widget
Create application Main window : To create a text box to receive user input
window=Tk() e=Entry( )
It calls a constructor of class Tk( ) in Tkinter module. Properties of Entry Widget
To change default title 1. fg - foreground color
window.title(“My title”) 2. bg - background colour(label colour)
To set the dimension of window 3. width- width
window.geometry(“400x400”) 4. height- height
 get( ) is used to access the text in Entry widget
To change background colour
window.configure(bg=”red”) Eg:-
To make window non resizable from tkinter import *
window.resizable(height=False,width=False) from tkinter import messagebox
1) Label Widget def test():
A label is created as follows t=e.get()
from tkinter import * messagebox.showinfo( 'Text is '+ t)
window=Tk() window=Tk()
l=Label(window, text=”My Label”) e=Entry(window,fg="red")
l.pack() b=Button(window, text='click' ,command=test)
Properties of Label Widget e.pack()
1) fg - foreground color b.pack()
2) bg - background colour(label colour) window.mainloop( )
3) width- width 5) Canvas
4) height- height Canvas is a rectangular area to place graphics,text, and widgets
Methods to display Widgets on window Syntax:
1) pack() Canvas(window,option=value)
2) grid() Properties of Canvas
3) place() 1. bg - background colour
2) MessageBox Widget 2. cursor-cursor icon can be changed to arrow,circle, dot.
Used to display the message boxes 3. Height - height of canvas
Syntax: 4. width- width of canvas
messagebox.Function_Name(title, message) Note:-
Function_Name: create_line(), create_arc(), create_oval( ), create_rectangle()
functions available in the messagebox widget are. are used to draw line, arc, oval, rectangle on a canvas
1. showinfo(): Show some information to the user. The following creates a canvas and draws a red line on it
2. showwarning(): Display the warning to the user. from tkinter import *
3. showerror(): Display the error message to the user window=Tk()
title: - title of message box. c=Canvas(window,bg=”blue”,height=200,width=200)
message: - message on the message box. c.create_line(0,0.200,200,fill=”red”)
Egs:- c.pack()
messagebox.showinfo("showinfo", "Information") window.mainloop()
messagebox.showwarning("showwarning","Warning") The following creates a canvas and insert an image on it
messagebox.showerror("showerror", "Error") c=Canvas(window,bg=”blue”, height=200,width=200)
3) Button Widget img=PhotoImage(file=”flower.png”)
A button is created as follows c.create_image(50,10,image=img,anchor=NW)
1
6) Checkbutton 7) Radiobutton
A checkbutton widget is used to display a number of A radiobutton widget is used to display a number of options
options ,from which a user can select one or more options from which a user can select only one option
c=Checkbutton(window,option=value) In order to implement this functionality, each group of
options can be.... radiobuttons must be associated to the same variable
1) bg - background colour syntax
2) fg - text colour r= Radiobutton( window, option, …)
3) activebackground -Active Background colour options can be...
4) activeforeground - Active Text colour I 1) activebackground- Active background color
5) cursor - pattern of cusor(dot,arrow,circle) 2) activeforeground- Active foreground color
6) height - height 3) bg -The normal background color
7) width - width 4) fg - text color
8) offvalue - Value to set when checkbutton is not selected 5) height - The number of lines of text. Default is 1.
9) onvalue - Value to set when checkbutton is checked 6) width -Width
10) variable - variable associated with tkinter variable 7) selectcolor- Radiobutton color when it is set. Default is red.
11) command -It is associated with a function 8) value - When a radiobutton is turned on by the user, its
Methods related to checkbutton control variable is set to its current value option
select() - To check a checkbutton 9) variable :The control variable that this radiobutton shares
deselect()- To uncheck a checkbutton with the other radiobuttons in the group
toggle() - To toggle the states methods
Tkinter control variables select() - Sets (turns on) the radiobutton.
 It is not possible to hand over a regular Python variable to a deselect() - Clears (turns off) the radiobutton
widget through a variable or textvariable option. Example
 The only kinds of variables for which this works are from tkinter import *
variables that are subclassed from a class called Variable, from functools import partial
defined in the Tkinter module. def sel():
They are created as follows selection = "You selected the option " + str(var.get())
x=StringVar(), label.config(text = selection)
x=IntVar() window = Tk()
x=DoubleVar() var = IntVar()
x = BooleanVar() r1 = Radiobutton(window , text="Option 1", variable=var,
How to associate a Entry text with StringVar value=1,command=sel)
var=StringVar() r1.pack( )
e=Entry(window,textvariable=var) r2 = Radiobutton(window, text="Option 2", variable=var,
How to associate a Label text with StringVar value=2, command=sel)
var=StringVar() r2.pack( )
l=Label(window,textvariable=var) r3 = Radiobutton(window, text="Option 3", variable=var,
How to associate a Check button value with IntVar() value=3, command=sel)
var=IntVar() r3.pack( )
c=Checkbutton(window,text=”Music”,variable=var) l = Label(window)
Example l.pack()
from tkinter import * window.mainloop()
def setval(): 8) Listbox
if (var1.get()==1) & (var2.get()==0): The Listbox widget is used to display a list of items from
l.config(text='You Love Music') which a user can select a number of items.
elif(var1.get() == 0) & (var2.get() == 1): syntax
l.config(text=’You Love Dance’) listbox= Listbox( window, option, ... )
elif (var1.get() == 1) & (var2.get() == 1): options can be...
l.config(text='You Love Music&Dance') 1. bg -The normal background color
else: 2. bd-The size of the border. Default is 2 pixels.
l.config(text='You Love neither' ) 3. fg -The color of the text in listbox
window = Tk() 4. font -The font used for the text in the listbox..
window.title('My Window') 5. height - The number of lines (not pixels) of text on the
window.geometry('100x100') Listbox. Default is 10.
l = Label(window, bg='white', width=20) 6. width- The width of the widget in characters. Default is 20.
l.pack() 7. selectmode -
var1 =IntVar()  BROWSE− Normally, you can only select one line out of a
var2 = IntVar() listbox. If you click on an item and then drag to a different
c1=Checkbutton(window,text='Music',variable=var1, line, the selection will follow the mouse. This is the default.
onvalue=1, offvalue=0, command=setval)  SINGLE− You can only select one line, and you can't drag
c2=Checkbutton(window,text='C++',variable=var2, the mouse.
onvalue=1, offvalue=0, command=setval)  MULTIPLE− You can select any number of lines at once.
c1.pack() Clicking on any line toggles whether or not it is selected.
c2.pack()  EXTENDED− You can select any adjacent group of lines
window.mainloop() at once by clicking on the first line and dragging to the last
line.
2
8. selectbackground - The background color to use To access current selected value
displaying selected text. value = combobox.get()
Methods To add items to combo box
1. delete ( first, last ) - delete the items in the list box combobox['values'] = ('value1', 'value2', 'value3')
( index ranges from first number (index) to last index #The combobox has the values property that you can assign a
specified). Index values in list box starts from 0 list of values
Eg:-list. delete(0,3) - deletes 4 items at index values 0-3 Layout management in Tkinter
2. delete(ANCHOR) – delete the selected item In Tkinter there are three types of layout managers
3. insert ( index, *elements ) - Insert one or more new lines - pack , place , and grid .
into the listbox before the line specified by index. Python Files
Eg:- list.insert(0,”first item”,”second item”) - This Files are named locations on disk to store related information.
command adds 2 items to the beginning of list They are used to permanently store data in a non-volatile
4. insert (END, *elements ) -Use END as the first argument memory (e.g. hard disk).
if you want to add new lines to the end of the listbox. When we want to read from or write to a file, we need to open
Eg: list.insert(END,”item1”,”item2”) - This command it first. When we are done, it needs to be closed so that the
adds 2 items at the end of of list resources that are tied with the file are freed.
5. size( ) - Returns the number of lines in the listbox Hence, in Python, a file operation takes place in the following
6. get ( first, last) -Returns a tuple containing the text of the order:
lines with indices from first to last, inclusive.  Open a file
Eg:- list.get(0,2) - This command is used to get first 3 items  Read or write (perform operation)
List box program  Close the file
from tkinter import * Opening Files in Python
def del1(): Python has a built in open() function to open a file, This
list.delete(ANCHOR) function returns a file object, also called a handle, as it is used
def ins(): to read or modify the file accordingly
item=e.get() f = open("test.txt") # open file in current directory
list.insert(END,item) f = open("C:/Python38/README.txt") # specifying full path
def disp(): Python File Modes
print(listbox.get(0,END)) We can specify the mode while opening a file. In mode, we
window = Tk() specify whether we want to read r, write w or append a to the
window.geometry("800x600") file.
l=Label(window,text="A list of favourite countries...") Mode Description
e=Entry(window) r Opens a file for reading. (default)
e.pack() w Opens a file for writing. Creates a new file if it
list=Listbox(window,selectmode=EXTENDED) does not exist or truncates the file if it exists.
list.insert(1,"India") x Opens a file for exclusive creation. If the file
list.insert(2, "USA") already exists, the operation fails
list.insert(3,"Japan") a Opens a file for appending at the end of the file
#this button will delete the selected item from the list without truncating it. Creates a new file if it does
btn1=Button(window, text = "delete",command=del1) not exist.
#this button insert the item in the Entry to the end of listbox Closing Files in Python
btn2=Button(window, text = "insert",command=ins) Closing a file will free up the resources that were tied with the
#this button will display a tuple containing all items in the list file. It is done using the close() method available in Python.
btn3=Button(window, text = "display",command=disp) f = open("test.txt")
l.pack() f.close()
list.pack() Writing to Files in Python
btn1.pack() In order to write into a file in Python, we need to open it in
btn2.pack() write w, append aor exclusive creation x mode.
btn3.pack() We need to be careful with the w mode, as it will overwrite
window.mainloop() into the file if it already exists. Due to this, all the previous
5. combobox data are erased.
A combobox widget allows you to select one value in a set of f=open("test.txt",'w')
values. f.write("my first file\n")
 To Create a combobox f.close()
To create a combobox widget, you’ll use the ttk.Combobox() Reading Files in Python
constructor.
To read a file in Python, open the file in reading rmode.
from tkinter import ttk
f = open("test.txt",'r')
The following example creates a combobox widget and
f.read()
links it to a string variable
f.close()
var = tk.StringVar()
readline() method to read individual lines of a file. This
combobox = ttk.Combobox(container, textvariable=var)
method reads a file till the newline, including the newline
# The container is the window or frame on which you want to
character.
place the combobox widget.
f = open("test.txt",'r')
#The textvariable argument links a variable var to the current
f.readline()
value of the combobox.
f.close()
3
Python Errors and Built-in Exceptions 3) GUI Program to illustrate button and message box
We can make certain mistakes while writing a program that widget
lead to errors when we try to run it. A python program Program:
terminates as soon as it encounters an unhandled error. These from tkinter import *
from tkinter import messagebox
errors can be broadly classified into two classes:
def clickaction( ):
1. Syntax errors messagebox.showinfo( "Click Command Action","Button
2. Exceptions clicked")
Python Syntax Errors window=Tk()
Error caused by not following the proper structure (syntax) of window.title("Button and Message Box")
the language is called syntax error or parsing error. window.geometry("300x100")
Let's look at one example: b1=Button( window, text="Click", fg="white", bg="blue",
if a < 3 width=10, height=2, command=clickaction)
File "<interactive input>", line 1 if a < 3 b1.place(x=50, y=30)
^ b2=Button(window, text="Exit", fg="white", bg="red",
SyntaxError: invalid syntax width=10, height=2,command=window.destroy)
As shown in the example, an arrow indicates where the parser b2.place(x=180, y=30)
ran into the syntax error. We can notice here that a colon : is window.mainloop()
missing in the if statement. Output:
Exceptions
Errors that occur at runtime (after passing the syntax test) are
called Exceptions.Whenever these types of runtime errors
occur, Python creates an exception object. If not handled
properly, it prints a traceback to that error along with some
details about why that error occurred.
Exception Cause of Error 4) GUI Program to create a simple feedback form
IndexError Raised when the index of a sequence is out Program:
of range. from tkinter import *
NameError Raised when a variable is not found in window=Tk()
local or global scope. window.title("FEEDBACK")
TypeError Raised when a function or operation is window.geometry("300x250")
applied to an object of incorrect type. lab=Label( window, text="FEEDBACK FORM",font=('Times',
ValueError Raised when a function gets an argument of 20))
correct type but improper value. lab.pack()
ZeroDivisionError Raised when the second operand of
division or modulo operation is zero.
lab1=Label( window, text="Name")
IndentationError Raised when there is incorrect indentation.
lab1.place(x=30, y=60)
Python GUI Programs ent1=Entry(window,fg="red") ent1.place(x=150, y=60)
1) GUI Program to illustrate Label widget lab3=Label( window, text="Phone No.")
Program: lab3.place(x=30, y=90)
from tkinter import * ent3=Entry(window,fg="red")
window=Tk() ent3.place(x=150, y=90)
window.title("Label Widget") lab2=Label( window, text="Message")
window.geometry("400x200") lab2.place(x=30, y=120)
l=Label( window,text="This is a Label",fg="blue", ent2=Entry(window,fg="red")
bg="yellow", width=40,height=2) ent2.place(x=150, y=120)
l.pack() but1=Button( window, text="SEND")
window.mainloop() but1.place(x=150, y=150)
Output: window.mainloop()
Output:

2) GUI Program to illustrate Entry Box widget


Program:
from tkinter import *
window=Tk()
window.title("EntryWidget")
window.geometry("400x200")
ent = Entry(window, fg="red", bg="white", width=20,
font=("Times",20))
ent.pack()
window.mainloop()
Output:

4
5) GUI Program to illustrate Canvas 7.GUI Program to create a biodata form Program:
Program: from tkinter import *
from tkinter import * window = Tk() window.title("Canvas") window = Tk()
can = Canvas(window, bg="yellow",height=250, width=300) window.title("Biodata")
line = can.create_line(108, 120,320, 40,fill="green") window.geometry("400x300")
arc = can.create_arc(180, 150, 80,210, lab=Label( window, text="BIODATA",font=('Times', 20))
start=0,extent=220,fill="red") lab.pack()
oval = can.create_oval(80, 30, 140,150,fill="blue") can.pack() lab1=Label(window,text="Name",fg="blue",font=('Times',
window.mainloop() 12))
Output: lab1.place(x=30, y=60)
ent1=Entry(window,fg="red") ent1.place(x=150, y=60)
lab3=Label(window,text="PhoneNo.",fg="blue",font=('Times',
12))
lab3.place(x=30, y=90)
ent3=Entry(window,fg="red")
ent3.place(x=150, y=90)
lab2=Label( window, text="Email",fg="blue",font=('Times',
12))
lab2.place(x=30, y=120)
ent2=Entry(window,fg="red")
ent2.place(x=150, y=120)
6) Program to illustrate Checkbox and Radio button lab1=Label(window,text="Hobbies",fg="blue",height=1,font=
Program: ('Times',12)) lab1.place(x=30,y=150)
from tkinter import * chkvar1 = IntVar()
window = Tk() chkvar2 = IntVar()
window.title("CheckBox and Radio Button") chkvar3 = IntVar()
window.geometry("400x200") chk1 = Checkbutton(window, text='Cricket',variable=chkvar1,
lab1=Label( window, text="Programming Language onvalue=1, offvalue=0)
",fg="blue",height=1) chk1.place(x=150,y=150)
lab1.place(x=20,y=30) chk2 = Checkbutton(window, text='Football',variable=chkvar2,
chkvar1 = IntVar() onvalue=1, offvalue=0)
chkvar2 = IntVar() chk2.place(x=230,y=150)
chkvar3 = IntVar() chk3 = Checkbutton(window, text='Reading',variable=chkvar3,
chk1 = Checkbutton(window, text='Python',variable=chkvar1, onvalue=1, offvalue=0)
onvalue=1, offvalue=0) chk3.place(x=300,y=150)
chk1.place(x=200,y=30) lab2=Label( window, text="Gender",fg="blue",height=1,
chk2 = Checkbutton(window, text='C++',variable=chkvar2, font=('Times',12)) lab2.place(x=30,y=180)
onvalue=1, offvalue=0) radvar = IntVar()
chk2.place(x=280,y=30) rad1 = Radiobutton(window, text="Male", variable=radvar,
chk3 = Checkbutton(window, text='PHP',variable=chkvar3, value=1)
onvalue=1, offvalue=0) rad1.place(x=150,y=180)
chk3.place(x=330,y=30) rad2 = Radiobutton(window, text="Female", variable=radvar,
lab2=Label( window, text="Operating System value=2)
",fg="blue",height=1) rad2.place(x=200,y=180)
lab2.place(x=20,y=70) but1=Button( window, text="SAVE") but1.place(x=150,
radvar = IntVar() y=210)
rad1 = Radiobutton(window, text="Windows", window.mainloop()
variable=radvar, value=1) Output:
rad1.place(x=200,y=70)
rad2 = Radiobutton(window, text="Linux", variable=radvar,
value=2)
rad2.place(x=280,y=70) window.mainloop()
Output:

You might also like