Python Unit-4 - Part-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

PROGRAMMING IN PYTHON

UNIT – 4 GUI Programming


 Event‐Driven Programming :
An event‐driven program is also known as an event‐driven application is a program designed to react to
specific kinds of user input such as clicks on a command button, choosing a choice from a drop‐down
list, adding an entry into a text box, or other kinds of user events.

Event‐driven programming separates event‐processing logic from the rest of a program’s code. The
event‐driven approach contrasts with batch processing. Because event‐driven programming is an
approach rather than a type of language, event‐driven apps can be created in any programming
language. Depending on the specific application, event‐driven processing can improve responsiveness,
throughput and flexibility.

 Event Handling :
Event Handling is having a function or method containing program statements that are executed when
an event occurs. An event handler typically is a software routine that processes actions such as
keystrokes and mouse movements. Event‐driven programming in python depends upon an event loop
that is always listening for the new incoming events.

 GUI PROGRAMMING :

Python provides several different options for writing GUI based programs. These are listed below:

 Tkinter − Tkinter is Python's standard GUI (graphical user interface) package. It is the most commonly
used toolkit for GUI programming in Python.

 wxPython − It is an open‐source, cross‐platform GUI toolkit written in C++. It is one of the


alternatives to Tkinter, which is bundled with Python.

 JPython − JPython is a Python port for Java which gives Python scripts seamless access to Java class
libraries on the local machine.

 GUI using tkinter :

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI
methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI
toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task.

To create a tkinter app:


1. Importing the module – tkinter : import tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

Page : 1
PROGRAMMING IN PYTHON
There are two main methods used which the user needs to create the Python application with GUI.

 Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):


To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to
the desired one. The basic code used to create the main window of the application is:

m=tkinter.Tk() #where m is the name of the main window object

 mainloop():
There is a method known by the name mainloop() is used when your application is ready to run.
mainloop() is an infinite loop used to run the application, wait for an event to occur and process the
event as long as the window is not closed.

r.mainloop()

Example :
import tkinter
r = tkinter.Tk()
'''
widgets are added here
'''
r.mainloop()

 Geometric Configuration :
tkinter also offers access to the geometric configuration of the widgets which can organize the
widgets in the parent windows. There are mainly three geometry manager classes :

1. pack() method : It organizes the widgets in blocks before placing in the parent widget.
2. grid() method : It organizes the widgets in grid (table‐like structure) before placing in the parent
widget.
3. place() method : It organizes the widgets by placing them on specific positions directed by the
programmer.

 WIDGETS :

Widget Description
Label The Label widget is used to provide a single‐line caption for other widgets.
Button The Button widget is used to display buttons in your application.
Entry The Entry widget is used to display a single‐line text field for accepting
values from a user.
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.
Checkbutton The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.
Message The Message widget is used to display multiline text fields for accepting
values from a user.

Page : 2
PROGRAMMING IN PYTHON
tkMessageBox This module is used to display message boxes in your applications.
Listbox The Listbox widget is used to provide a list of options to a user.
Scrollbar The Scrollbar widget is used to add scrolling capability to various widgets,
such as list boxes.
Frame The Frame widget is used as a container widget to organize other widgets.
Canvas The Canvas widget is used to draw shapes, such as lines, ovals, polygons
and rectangles, in your application.
Menubutton The Menubutton widget is used to display menus in your application.
Menu The Menu widget is used to provide various commands to a user. These
commands are contained inside Menubutton.
Scale The Scale widget is used to provide a slider widget.
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.
Toplevel The Toplevel widget is used to provide a separate window container.

 Label :
It refers to the display box where you can put any text or image which can be updated any time as per
the code.

Syntax :
w=Label(master, option=value)

Options :
• bg: to set the normal background color.
• fg to set the normal foreground color.
• command: to call a function.
• font: to set the font on the button label.

Example :
from tkinter import *
r = Tk()
r.geometry("400x100")
w = Label(r, text='Welcome to the world of Python',font="algerian",bg="yellow",fg="red")
w.pack()
r.mainloop()

 Button :
The Button widget is used to add buttons in a Python application. These buttons can display text or
images that convey the purpose of the buttons.

Syntax:
w=Button(master, option=value)

Options :
• activebackground: to set the background color when button is under the cursor.
• activeforeground: to set the foreground color when button is under the cursor.
• bg: to set the normal background color.
• command: to call a function.

Page : 3
PROGRAMMING IN PYTHON
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height: to set the height of the button.

Example :
import tkinter as tk
r = tk.Tk()
r.title('Button Example')
r.geometry('500x200')
button = tk.Button(r, text='click me', width=25, command=r.destroy)
button.pack()
r.mainloop()

 Entry :
It is used to input the single line text entry from the user. For multi‐line text input, Text widget is used.

Syntax :
w=Entry(master, option=value)

Options :
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• command: to call a function.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the button.
• height: to set the height of the button.

Example :
from tkinter import *
r = Tk()
Label(r, text='First Name').grid(row=0)
Label(r, text='Last Name').grid(row=1)
e1 = Entry(r,highlightthickness=2,highlightcolor="red")
e2 = Entry(r,highlightthickness=2,highlightcolor="red")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
r.mainloop()

 RadioButton :
It is used to offer multi‐choice option to the user. It offers several options to the user and the user has
to choose one option.

Syntax :
w = RadioButton(master, option=value)

Page : 4
PROGRAMMING IN PYTHON
Options :
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the label in characters.
• height: to set the height of the label in characters.

Example :
from tkinter import *
from tkinter import messagebox
r = Tk()
r.title('Choose your Education')
r.geometry('300x100')
def sel():
choice = var.get()
if choice == 1:
output = "HSC"
elif choice == 2:
output = "Graduate"
elif choice == 3:
output = "Post Graduate"
else:
output = "Invalid selection"
return messagebox.showinfo('Your Selection is :',f'You Selected {output}.')

var = IntVar()
R1 = Radiobutton(r, text="HSC", variable=var, value=1, command=sel).pack()
R2 = Radiobutton(r, text="Graduate", variable=var, value=2, command=sel).pack()
R3 = Radiobutton(r, text="Post Graduate", variable=var, value=3, command=sel).pack()
r.mainloop()

 CheckButton :
To select any number of options by displaying a number of options to a user as toggle buttons.

Syntax :
w = CheckButton(master, option=value)

Options :
• Title: To set the title of the widget.
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set the normal background
• command: to call a function.
• font: to set the font on the button label.

Page : 5
PROGRAMMING IN PYTHON
Example :
from tkinter import *
r = Tk()
r.title("Hobbies")
r.geometry("300x100")

l=Label(r,text="Choose your hobbies",font="Arial").grid(row=1)


var1 = IntVar()
Checkbutton(r, text='cricket', variable=var1).grid(row=2,sticky=W)
var2 = IntVar()
Checkbutton(r, text='football', variable=var2).grid(row=3,sticky=W)
var3 = IntVar()
Checkbutton(r, text='hockey', variable=var3).grid(row=4,sticky=W)
r.mainloop()

 Message :
It refers to the multi‐line and non‐editable text. It works same as that of Label.

Syntax :
w = Message(master, option=value)

Options :
• bd: to set the border around the indicator.
• bg: to set he normal background color.
• font: to set the font on the button label.
• width: to set the width of the widget.
• height: to set the height of the widget.

Example :
from tkinter import *
r = Tk()
msg ='Welcome to the world of Python'
messageVar = Message(r, text=msg,bg="lightpink")
messageVar.pack( )
r.mainloop( )

 tkMessageBox :
The tkMessageBox module is used to display message boxes in your applications. This module provides
a number of functions that you can use to display an appropriate message.

Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, and
askyesno.

Syntax :
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 tle bar of a message box.

Page : 6
PROGRAMMING IN PYTHON
• message − This is the text to be displayed as a message.
• options − op ons are alterna ve 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.

Example :
import tkinter as tk
from tkinter import messagebox
r = tk.Tk()
def greet():
messagebox.showinfo("Greetings", "Welcome to world of Python")
B1 = tk.Button(r, text = "Click Me", command = greet)
B1.pack()
r.mainloop()

 ListBox :
It offers a list to the user from which the user can accept any number of options.

Syntax :
w = Listbox(master, option=value)

Options :
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bg: to set the normal background color.
• bd: to set the border width in pixels.
• font: to set the font on the button label.
• selectbackground : The background color to use displaying selected text.
• selectmode : Determines how many items can be selected, and how mouse drags affect the
selection –
o SINGLE − You can only select one line, and you can't drag the mouse, wherever you click button
1, that line is selected.
o MULTIPLE − You can select any number of lines at once. Clicking on any line toggles whether or
not it is selected.
o EXTENDED − You can select any adjacent group of lines at once by clicking on the first line and
dragging to the last line.

Example :
from tkinter import *
r = Tk()
Lb = Listbox(r,selectmode="single")
Lb.insert(1, 'JavaScript')
Lb.insert(2, 'Java')
Lb.insert(3, 'WordPress')
Lb.insert(4, 'Python')
Lb.pack()
r.mainloop()

Page : 7
PROGRAMMING IN PYTHON
 Scrollbar :
It refers to the slide controller which will be used to implement listed widgets

Syntax :
w = Scrollbar(master, option=value)

Options :
• width: to set the width of the widget.
• activebackground: To set the background when mouse is over the widget.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.

Example :
from tkinter import *
r = Tk()
scrollbar = Scrollbar(r)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(r, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()

 Frame :
The Frame widget is very important for the process of grouping and organizing other widgets in a
somehow friendly way. It works like a container, which is responsible for arranging the position of
other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of these widgets.
A frame can also be used as a foundation class to implement complex widgets.

Syntax :
w = Frame(master, option=value)

Options :
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.

Example :
from tkinter import *
r = Tk()
frame = Frame(r)
frame.pack()

Page : 8
PROGRAMMING IN PYTHON
bottomframe = Frame(r)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(bottomframe, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
r.mainloop()

 Canvas :
It is used to draw pictures and other complex layout like graphics, text and widgets.

Syntax:
w = Canvas(master, option=value)

Options :
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used in the canvas.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the widget.
• height: to set the height of the widget.

Example :
from tkinter import *
r = Tk()
w = Canvas(r, bg='yellow', width=200, height=200)
w.pack()
canvas_height=200
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
w.create_rectangle(50, 20, 150, 80, fill="red")
r.mainloop()

 Menu :
It is used to create all kinds of menus used by the application.

Syntax :
w = Menu(master, option=value)

Options :
• title: To set the title of the widget.
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.

Page : 9
PROGRAMMING IN PYTHON
• bg: to set the normal background color.
• command: to call a function.

 Menubutton :
It is a part of top‐down menu which stays on the window all the time. Every menubutton has its own
functionality.

Syntax :
w = MenuButton(master, option=value)

Options :
• activebackground: To set the background when mouse is over the widget.
• activeforeground: To set the foreground when mouse is over the widget.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• type (index) : Returns the type of the choice specified by index: either "cascade", "checkbutton",
"command", "radiobutton", "separator", or "tearoff".

Example :
from tkinter import *
def msg():
nw = Toplevel(root)
button = Menubutton(nw, text="You have clicked NEW Option")
button.pack()
def msg1():
nw = Toplevel(root)
button = Menubutton(nw, text="You have clicked Open Option")
button.pack()

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New',command=msg)
filemenu.add_command(label='Open',command=msg1)
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu,tearoff=0)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

 Scale :
It is used to provide a graphical slider that allows to select any value from that scale.

Page : 10
PROGRAMMING IN PYTHON
Syntax :
w = Scale(master, option=value)

Options :
• cursor: To change the cursor pattern when the mouse is over the widget.
• activebackground: To set the background of the widget when mouse is over the widget.
• bg: to set the normal background color.
• orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
• from_: To set the value of one end of the scale range.
• to: To set the value of the other end of the scale range.
• width: to set the width of the widget.

Example :
from tkinter import *
r = Tk()
w = Scale(r, from_=0, to=42)
w.pack()
w = Scale(r, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

 Spinbox :
It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.

Syntax :
w = SpinBox(master, option=value)

Options :
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• command: To call a function.
• width: to set the width of the widget.
• activebackground: To set the background when mouse is over the widget.
• disabledbackground: To disable the background when mouse is over the widget.
• from_: To set the value of one end of the range.
• to: To set the value of the other end of the range.

Example :
from tkinter import *
r = Tk()
w = Spinbox(r, from_ = 0, to = 20)
w.pack()
mainloop()

 Toplevel :
This widget is directly controlled by the window manager. It don’t need any parent window to work on.

Page : 11
PROGRAMMING IN PYTHON
Syntax :
w = TopLevel(master, option=value)

Options :
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• width: to set the width of the widget.
• height: to set the height of the widget.

Example :
from tkinter import *
r = Tk()
r.geometry("200x200")
def open():
top = Toplevel(r)
top.mainloop()

btn = Button(r, text = "open", command = open)


btn.place(x=75,y=50)
r.mainloop()

Page : 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy