Unit5 PP

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

Department of Computer

Science and Engineering

PYTHON P R O G R A M M I N G
Course Code : 10211CS213
Course Name : Python Programming
Course Faculty : Mrs. M. Divya
Category : Program Core
Slot Number : S3L18
Unit : V

School of Computing
Vel Tech Rangarajan Dr. Sagunthala R&D Institute of
Science and Technology
10/17/2024 1
UNIT 5 UI and Game design using Python
libraries

UI and Game design using Python libraries T+L- 3+3 Hours


Tkinter module: introduction, widgets, standard
attributes, Geometry management, Tkinter Event Handling;
Database connectivity with MySQL. PyGame Module - PyGame
Concepts- Basic Game Design-Sprites-Sprite Groups-Custom Events-
Collision Detection-Sprite Images-Game Speed-Sound Effects.
Case Studies: Angry bird game and UI design

2
October 17, 2024 Python Programming
Tkinter: Introduction
➢ Python provides the standard library Tkinter for creating the graphical user interface
for desktop based applications.
➢ Tkinter was written by Guido van Rossum and Steen Lumholt, later revised by Fredrik
Lundh. Tkinter is free software released under a Python license.
➢ Developing desktop based applications with python Tkinter is not a complex task. An
empty Tkinter top-level window can be created by using the following steps.
✓ import the Tkinter module.
✓ Create the main application window.
✓ Add the widgets like labels, buttons, frames, etc. to the window.
✓ Call the main event loop so that the actions can take place on the user's
computer screen.
October 17, 2024 Python Programming 3
python --version

Tkinter

◼ Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.

◼ Tkinter: Python interface to the Tk GUI toolkit

◼ wxPython: written in C++,

◼ JPython: Python scripts seamless access to Java class libraries

◼ Python Tkinter installation


◼ >>python --version

◼ >>pip install tk

October 17, 2024 Python Programming 4


Tkinter
Sample Program Using Tkinter without Widgets

Tkinter Simple Programming

#!/usr/bin/python

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

October 17, 2024 Python Programming 5


Tkinter widgets
◼ There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the
python GUI applications.

1. Button 11. Radiobutton


2. Canvas 12. Scale
3. Checkbutton 13. Scrollbar
4. Entry 14. Text
5. Frame 15. Toplevel
6. Label 16. Spinbox
7. ListBox 17. PanedWindow
8. Menubutton 18. LabelFrame
9. Menu 19. MessageBox
10. Message
Python Programming 6
October 17, 2024
Python Tkinter Geometry

The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry methods.

1. The pack() method : it represents the side of the direction to which the widget,
to be placed
syntax
widget.pack(options)
2. The grid() method : it organizes the widgets in the tabular form
syntax
widget.grid(options)
3. The place() method : it places the widgets to the specific x and y coordinates.
syntax
widget.place(options)

October 17, 2024 Python Programming 7


Python Tkinter grid() method
# !/usr/bin/python3
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

October 17, 2024 Python Programming 8


Python Tkinter Button
Button
The Button is used to add various kinds of buttons to the python application.
Syntax :

W = Button(parent, options)

#python application to create a simple button


from tkinter import *
top = Tk()
top.geometry("200x100")
b = Button(top,text = "Simple")
b.pack()
top.mainloop()
October 17, 2024 Python Programming 9
Python Tkinter Button
#python application to create a simple 4 buttons
from tkinter import *
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top,text = "Red",command = fun, activeforeground = "red",activebackground = "pink")


b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink")
b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink")
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink")

b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)

top.mainloop()

October 17, 2024 Python Programming 10


Python Tkinter Canvas
◼ The canvas widget is used to add the structured graphics to the python application.
◼ It is used to draw the graph and plots to the python application.
Syntax :
w = canvas(parent, options)

#Creating an circle, ellipse, rectangle


from tkinter import *
top = Tk()
top.geometry("500x500")
# creating a simple canvas
c = Canvas(top, bg="pink", height="500", width=500)
circle = c.create_oval(10, 10, 80, 80, outline = "black", fill = "white", width = 2)
ellipse = c.create_oval(110, 10, 210, 80, outline = "red", fill = "green", width = 2)
rectangle = c.create_rectangle(230, 10, 290, 60, outline = "black", fill = "blue", width = 2)
c.pack()
top.mainloop()
October 17, 2024 Python Programming 11
Python Tkinter Checkbutton
• The Checkbutton can contain the text or images.
• The Checkbutton is mostly used to provide many choices to the user

Syntax :
w = checkbutton(master, options)

#creating check button


from tkinter import *
top = Tk()
top.geometry("200x200")

checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()

chkbtn1 = Checkbutton(top, text="C", variable=checkvar1, onvalue=1, offvalue=0, height=2, width=10)


chkbtn2 = Checkbutton(top, text="C++", variable=checkvar2, onvalue=1, offvalue=0, height=2, width=10)
chkbtn3 = Checkbutton(top, text="Java", variable=checkvar3, onvalue=1, offvalue=0, height=2, width=10)
October 17, 2024 Python Programming 12
Python Tkinter Checkbutton

chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()

top.mainloop()

October 17, 2024 Python Programming 13


Python Tkinter Entry
The Entry widget is used to provide the single line text-box to the user to accept a value from the user

#single line text-box using entry widget Syntax :


# !/usr/bin/python3 w = Entry (parent, options)
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text="Name").place(x=30, y=50)
email = Label(top, text="Email").place(x=30, y=90)
password = Label(top, text="Password").place(x=30, y=130)
sbmitbtn = Button(top, text="Submit", activebackground="pink",
activeforeground="blue").place(x=30, y=170)
e1 = Entry(top).place(x=80, y=50)
e2 = Entry(top).place(x=80, y=90)
e3 = Entry(top).place(x=95, y=130)
top.mainloop()
October 17, 2024 Python Programming 14
Python Tkinter Frame
• Python Tkinter Frame widget is used to organize the group of widgets. Syntax :
• It acts like a container which can be used to hold the other widgets. w = Frame(parent, options)

from tkinter import * btn2 = Button(frame, text="Remove", fg="brown",


top = Tk() activebackground="brown")
top.geometry(“200x200") btn2.pack(side=RIGHT)
frame = Frame(top)
frame.pack() btn3 = Button(rightframe, text="Add", fg="blue",
activebackground="blue")
leftframe = Frame(top) btn3.pack(side=LEFT)
leftframe.pack(side=LEFT)
btn4 = Button(leftframe, text="Modify", fg="black",
rightframe = Frame(top) activebackground="white")
rightframe.pack(side=RIGHT) btn4.pack(side=RIGHT)

btn1 = Button(frame, text="Submit", fg="red", top.mainloop()


activebackground="red")
btn1.pack(side=LEFT)
October 17, 2024 Python Programming 15
Python Tkinter Listbox
The Listbox widget is used to display the list items to the user.
We can select only text items in the Listbox and all text items contain the same font and color.

Syntax :
w = Listbox(parent, options)

# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top, text="A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1, "India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Australia")

October 17, 2024 Python Programming 16


Python Tkinter Listbox

btn = Button(top, text="delete", command=lambda listbox=listbox: listbox.delete(ANCHOR))


lbl.pack()
listbox.pack()
btn.pack()
top.mainloop()

October 17, 2024 Python Programming 17


Python Tkinter Menubutton
• The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time.
• It is used to provide the user a option to select the appropriate choice exist within the application.
Syntax :
w = Menubutton(Top, options)

# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
mbutton = Menubutton(top, text="Language")
mbutton.grid()
mbutton.menu = Menu(mbutton)
mbutton["menu"] = mbutton.menu
mbutton.menu.add_checkbutton(label="Hindi", variable=IntVar())
mbutton.menu.add_checkbutton(label="English", variable=IntVar())
mbutton.pack()
October 17, 2024 Python Programming 18
Python Tkinter Menu
The Menu widget is used to create various types of menus (top level, pull down, and pop up) in the
python application.
Syntax :
w = Menu(top, options)

from tkinter import Toplevel, Button, Tk, Menu

top = Tk()
menubar = Menu(top)
file = Menu(menubar)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")

file.add_separator()
file.add_command(label="Exit", command=top.quit)
October 17, 2024 Python Programming 19
Python Tkinter Menu
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar)
edit.add_command(label="Undo")

edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")

menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)

top.config(menu=menubar)
top.mainloop()

October 17, 2024 Python Programming 20


Python Tkinter Radiobutton
The Radiobutton widget shows multiple choices to the user out of which, the user can select only one
out of them.
Syntax :
w = Radiobutton(top, options)

from tkinter import *

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

top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text="Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=selection)
R1.pack(anchor=W)
October 17, 2024 Python Programming 21
Python Tkinter Radiobutton

R2 = Radiobutton(top, text="C++", variable=radio, value=2, command=selection)


R2.pack(anchor=W)

R3 = Radiobutton(top, text="Java", variable=radio, value=3, command=selection)


R3.pack(anchor=W)

label = Label(top)
label.pack()
top.mainloop()

October 17, 2024 Python Programming 22


Python Tkinter Scale
The Scale widget is used to implement the graphical slider to the python application so that the user
can slide through the range of values shown on the slider and select the one among them.
Syntax :
w = Scale(top, options)

from tkinter import *

def select():
sel = "Value = " + str(v.get())
label.config(text=sel)

top = Tk()
top.geometry("200x100")
v = DoubleVar()
scale = Scale(top, variable=v, from_=1, to=50, orient=HORIZONTAL)
scale.pack(anchor=CENTER)

October 17, 2024 Python Programming 23


Python Tkinter Scale

btn = Button(top, text="Value", command=select)


btn.pack(anchor=CENTER)

label = Label(top)
label.pack()

top.mainloop()

October 17, 2024 Python Programming 24


Python Tkinter Scrollbar
The scrollbar widget is used to scroll down the content of the other widgets like listbox, text, and canvas.
We can also create the horizontal scrollbars to the Entry widget.
Syntax :
w = Scrollbar(top, options)
from tkinter import *
top = Tk()
sb = Scrollbar(top)
sb.pack(side=RIGHT, fill=Y)
mylist = Listbox(top, yscrollcommand=sb.set)

for line in range(30):


mylist.insert(END, "Number " + str(line))

mylist.pack(side=LEFT)
sb.config(command=mylist.yview)

mainloop()
October 17, 2024 Python Programming 25
Python Tkinter Text
The Text widget is used to show the text data on the Python application. Tkinter provides us the Entry
widget which is used to implement the single line text box.
Syntax :
w = Text(top, options)

from tkinter import *


top = Tk()
text = Text(top)

text.insert(INSERT, "Name.....")
text.insert(END, "Salary.....")

text.pack()

top.mainloop()

October 17, 2024 Python Programming 26


Tkinter Toplevel
The Toplevel widget is used to create and display the toplevel windows which are directly managed by the
window manager.
The toplevel widget is used when a python application needs to represent some extra information, pop-
up, or the group of widgets on the new window.
Syntax :
w = Text(top, options)

from tkinter import *


root = Tk()
root.geometry("200x200")

def open():
top = Toplevel(root)
top.mainloop()

btn = Button(root, text="open",


command=open)
btn.place(x=75, y=50)
root.mainloop()
October 17, 2024 Python Programming 27
Python Tkinter Spinbox
The Spinbox widget is an alternative to the Entry widget. It provides the range of values to the user, out
of which, the user can select the one.

Syntax :
w = Spinbox(top, options)

from tkinter import *

top = Tk()
top.geometry("200x200")
spin = Spinbox(top, from_=0, to=25)
spin.pack()
top.mainloop()

October 17, 2024 Python Programming 28


Tkinter PanedWindow
The PanedWindow widget acts like a Container widget which contains one or more child widgets (panes) arranged
horizontally or vertically.
The child panes can be resized by the user, by moving the separator lines known as sashes by using the mouse.
Each pane contains only one widget. The PanedWindow is used to implement the different layouts in the python
applications.

Syntax :
w = Spinbox(top, options)

# !/usr/bin/python3
from tkinter import *

def add():
a = int(e1.get())
b = int(e2.get())
leftdata = str(a + b)
left.insert(1, leftdata)
October 17, 2024 Python Programming 29
Tkinter PanedWindow
w1 = PanedWindow()
w1.pack(fill=BOTH, expand=1)

left = Entry(w1, bd=5)


w1.add(left)

w2 = PanedWindow(w1, orient=VERTICAL)
w1.add(w2)

e1 = Entry(w2)
e2 = Entry(w2)

w2.add(e1)
w2.add(e2)

bottom = Button(w2, text="Add", command=add)


w2.add(bottom)

mainloop()
October 17, 2024 Python Programming 30
Tkinter LabelFrame
• The LabelFrame widget is used to draw a border around its child widgets.
• It acts like a container which can be used to group the number of interrelated widgets such as
Radiobuttons.
• This widget is a variant of the Frame widget which has all the features of a frame. It also can display a
label.
Syntax :
w = LabelFrame(top, options)
# !/usr/bin/python3
from tkinter import *

top = Tk()
top.geometry("300x200")

labelframe1 = LabelFrame(top, text="Positive


Comments")
labelframe1.pack(fill="both", expand="yes")

October 17, 2024 Python Programming 31


Tkinter LabelFrame

toplabel = Label(labelframe1, text="Place to put the


positive comments")
toplabel.pack()

labelframe2 = LabelFrame(top, text="Negative


Comments")
labelframe2.pack(fill="both", expand="yes")

bottomlabel = Label(labelframe2, text="Place to put the


negative comments")
bottomlabel.pack()

top.mainloop()

October 17, 2024 Python Programming 32


Tkinter messagebox
The messagebox module is used to display the message boxes in the python applications.
There are the various functions which are used to display the relevant messages depending upon the
application requirements.

Syntax :
messagebox.function_name(title, message [, options])

Parameters
➢ function_name: It represents an appropriate message box function.
➢ title: It is a string which is shown as a title of a message box.
➢ message: It is the string to be displayed as a message on the message box.
➢ options: There are various options which can be used to configure the
message dialog box.

October 17, 2024 Python Programming 33


Tkinter messagebox
#showinfo() method
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showinfo("information","Information")
top.mainloop()

#showwarning() method
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showwarning("warning","Warning")

top.mainloop() 1
October 17, 2024 Python Programming 34
Tkinter messagebox
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("500x500")
messagebox.showerror("error","Error")
messagebox.askquestion("Confirm","Are you sure?")
messagebox.askokcancel("Redirect","Redirecting you to www.veltech.edu.in")
messagebox.askyesno("Application","Got It?")
messagebox.askretrycancel("Application","try again?")
top.mainloop()

October 17, 2024 Python Programming 35


PYGAME AGENDA

Gaming – Introduction

Setting Up your play Area


❖ Pygame Installation, Import And Intialization
❖ Setting up Screen for your game
❖ Game States and Game Loop
❖ Update and Exit Conditions
❖ Inserting Images
❖ Handling Events

10/17/2024 36
GAMING - INTRODUCTION
GUI Vs CLI

✓ Command Line Interface (Commands)


✓ Graphical User Interface (Graphical
Elements)

How Video Games works?


Sequence of frames running at a
specified speed
Frame rate
measurement of how quickly a number of
frames appears within a second
FPS – Frames Per Second

Play Area:
❖ Display Area (Canvas) SA1 SA2
❖ Surface area (Objects that gets placed Display Area
in display area)
Pygame is rarely used in Gaming Industry.
10/17/2024 37
PYGAME – Background and Setup

PYGAME is a Python wrapper for the SDL Library, which stands


for Simple DirectMedia Layer.
➔ Provides cross-platform access to your system’s
underlying multimedia hardware components.(such as sound,
video, mouse, keyboard, and joystick)

Installing Pygame library


In Command Prompt,
Move into the directory where you have your python
software installed and type
pip install pygame
In recent updated version of python we don’t have pygame, so use
previous version of pygame, so
pip install pygame --pre

10/17/2024 38
PYGAME INSTALLATION, IMPORT AND INTIALIZATION

Import pygame module

import pygame, sys


from pygame.locals import *

Intiallizing Pygame
pygame.init() # starts up pyGame

To start off our game, we must pop up a graphical window.


Creating a window(Display Area/ Canvas)
display.set_mode((width, height))
Arguments => A tuple (width, height) of screen in pixels.
Returns => an object of type Surface (screen)
We can call methods on the screen later.

10/17/2024 39
Setting up Screen for your game

Setting up Title for the window

display.set_caption => sets the window's title.


display.set_caption("title")

Setting up Background Color for the display area

fill((R, G, B))

This method is used to fill the display with the color specified.
• Argument: (Red, Green, Blue)
➔ RGB values to set the background color
(0, 0, 0) ➔ Black
(255, 255, 255) ➔ White
win.fill((0,0,0))

10/17/2024 40
GAME STATES AND GAME LOOP
Game State:
Refers to a set of values for all the variables in a game program.
Event:
(Clicking a mouse, Pressing a key) which affects the game state
Game state is usually updated in response to events
or the passage of time.

Game Loop
1. Handles events.
2. Updates the game state.
3. Draws the game state to the screen.
1. Event Handling:
The main code that updates the game state based on which events have been created.
To identify the event: pygame.event.get()
Returns ➔ a list of pygame.event.Event objects

10/17/2024 41
Pygame functions – Update and Exit conditions
2. Draws the Surface object and updates the display:
pygame.display.update()

pause the program for an amount of time


delay(milliseconds) -> time
pygame.time.delay(100)

EXIT CONDITION FOR GAME


Statements used in loops: (Break, Continue)
QUIT Event Type
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.quit() ➔ It runs code that deactivates the Pygame library.
sys.exit() ➔ terminate the program.

10/17/2024 42
Pygame functions – Inserting Images
Image module in pygame is for image transfer
Loads new image from a file (or file-like object)
returns ➔ Surface. The returned Surface will contain the same color
format, colorkey and alpha transparency as the file it came from.

pygame.image.load(Location of the file)

blit function: [blit stands for Block Image transfer]

blit(source_name, (x_dest, y_dest))

Draws one image onto another


Blits the surface on to the other surface in specified location.

blit(source_name, (dest_x, dest_y), area=None, special_flags=0)

10/17/2024 43
Pygame functions
Example:
catImg = pygame.image.load('F:\VTU\B.Tech_Python\
course_ready\pics\cat.png')
win.blit(catImg, (0, 0))
win.blit(catImg, (400, 400))

Handling Events:
pygame.key.get_pressed()

Gets the state of all keyboard buttons

Returns ➔ A sequence of boolean values representing the state of every key on the
keyboard.

Examples of Pygame Constants: [K_LEFT, K_RIGHT, K_UP, K_DOWN]

10/17/2024 44
Sample Game: Catch the Cat
# Simple pygame program
# Import and initialize the pygame library

import pygame
pygame.init()

# Set up the drawing window


win = pygame.display.set_mode((500, 500))
# Set Title for the gaming window
pygame.display.set_caption("Catch the Cat")

vel = 5
run = True
x=0
y=0

#Game Loop
while run:
#Setting the response time for the Event
pygame.time.delay(100)
# Look at every event in the queue
for event in pygame.event.get():
# Did the user click the window close button?
if event.type == pygame.QUIT:
run = False

10/17/2024 45
#Gets the state of all keyboard buttons
keys = pygame.key.get_pressed()
#If Left Arrow Key is Pressed
if keys[pygame.K_LEFT]:
x -= vel
#If Right Arrow Key is Pressed
if keys[pygame.K_RIGHT]:
x += vel
#If Up Arrow Key is Pressed
if keys[pygame.K_UP]:
y -= vel
#If Down Arrow Key is Pressed
if keys[pygame.K_DOWN]:
y += vel
#Fill the display with specified color
win.fill((0,0,0))
#Blit the Images to the Display Surfce(Canvas)
catImg = pygame.image.load('F:\VTU\B.Tech_Python\Course_ready\pics\cat.png')
win.blit(catImg, (x, y))
win.blit(catImg, (400, 400))
#Update the display
pygame.display.update()

#Quit the program


pygame.quit()

10/17/2024 46
Thank You
Any Queries

October 17, 2024 Python Programming 47

You might also like