0% found this document useful (0 votes)
26 views16 pages

Unit - 4 Lab Programs Ex 4.1 To 4.4

Uploaded by

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

Unit - 4 Lab Programs Ex 4.1 To 4.4

Uploaded by

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

Ex.No. 4.

1 Simple Registration Form using Tkinter

Aim:
Design a gui form with vertical box layout that includes labels and entry fields for
user registration in python.

Algorithm:
Step 1 : The first step is to import the tkinter module
(using either tkinter import * or just import tkinter).
Step 2 : The primary window of the GUI programme was created.
Step 3 : Include one or more widgets in the GUI programme (controls such as
buttons, labels, and text boxes, etc.).
Step 4 : Enter the primary events to react to each event that the user has triggered.

Coding
from tkinter import *
base = Tk()
base.geometry("500x500")
base.title("registration form")

lb1= Label(base, text="Enter Name", width=10, font=("arial",12))


lb1.place(x=20, y=120)
en1= Entry(base)
en1.place(x=200, y=120)

lb3= Label(base, text="Enter Email", width=10, font=("arial",12))


lb3.place(x=19, y=160)
en3= Entry(base)
en3.place(x=200, y=160)

lb4= Label(base, text="Contact Number", width=13,font=("arial",12))


lb4.place(x=19, y=200)
en4= Entry(base)
en4.place(x=200, y=200)

lb5= Label(base, text="Select Gender", width=15, font=("arial",12))


lb5.place(x=5, y=240)
vars = IntVar()
Radiobutton(base, text="Male", padx=5,variable=vars,
value=1).place(x=180, y=240)
Radiobutton(base, text="Female", padx =10,variable=vars,
value=2).place(x=240,y=240)
Radiobutton(base, text="others", padx=15, variable=vars,
value=3).place(x=310,y=240)

list_of_cntry = ("United States", "India", "Nepal", "Germany")


cv = StringVar()
drplist= OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set("United States")
lb2= Label(base, text="Select Country", width=13,font=("arial",12))
lb2.place(x=14,y=280)
drplist.place(x=200, y=275)

lb6= Label(base, text="Enter Password", width=13,font=("arial",12))


lb6.place(x=19, y=320)
en6= Entry(base, show='*')
en6.place(x=200, y=320)

lb7= Label(base, text="Re-Enter Password", width=15,font=("arial",12))


lb7.place(x=21, y=360)
en7 =Entry(base, show='*')
en7.place(x=200, y=360)

Button(base, text="Register", width=10).place(x=200,y=400)


base.mainloop()

output:
Result :
To design a GUI form with vertical box layout that includes labels and entry fields
for user registration in python was competed successfully.

Ex.No. 4.2: GUI window with a grid layout and buttons

Aim:

To create a GUI window with a grid layout that performs Tic-tac-toe game(3x3 board
game).

Algorithm:

• Import tkinter module and message box


• Create global variables Player and stop_game initialized to False

• Create a GUI window using tk() as the root window with title ‘Tic-Tac-Toe’

• Create a 2-dimensional array for storing the 9 positions as buttons

• Create buttons for each positions

• Assign height, width, font for the button

• Bind the button command to the function ‘clicked’ with its position as
arguments

• Attach button to root window using ‘grid’ layout with row and column values

• Create the function ‘clicked’ to perform the playing layout

• Check current player

• Add the player’s symbol to the given position

• Check if there is a win or tie condition

• Destroy the window when stop_game is True, otherwise continue playing

• Create the function ‘check_if_win to check if game is over

• Check if any row has the same symbol, display win status and stop_game =
True

• Check if any column has the same symbol, if yes display win status and
stop_game = True

• Check if any diagonal has the same symbol, display win status and
stop_game = True

• Check if all the 9 positions are filled: display tie and stop_game = True

Program:

from tkinter import *

from tkinter import messagebox

Player = 'X'#First player

stop_game = False
def clicked(r,c):

global Player

#X's turn

if Player == "X" and b[r][c]['text'] == '' and stop_game == False:

b[r][c].configure(text = "X")

Player='O'

#o's turn

if Player == 'O' and b[r][c]['text'] == '' and stop_game == False:

b[r][c].configure(text = 'O')

Player = "X"

#Check if game is over

check_if_win()

if stop_game == True:

root.destroy()

def check_if_win():

global stop_game

for i in range(3):

#Horizontal match

if b[i][0]['text'] == b[i][1]['text'] == b[i][2]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner", b[i][0]['text'] + " Won")

break

#Vertical Match

elif b[0][i]['text'] == b[1][i]['text'] == b[2][i]['text'] != '':


stop_game = True

winner = messagebox.showinfo("Winner", b[0][i]['text']+ " Won!")

break

#Left diagonal

elif b[0][0]['text'] == b[1][1]['text'] == b[2][2]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner", b[0][0]['text']+ " Won!")

break

#Right diagonal

elif b[0][2]['text'] == b[1][1]['text'] == b[2][0]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner" , b[0][2]['text']+ " Won!")

break

#Tie case

elif b[0][0]['text'] and b[0][1]['text'] and b[0][2]['text'] and b[1][0]['text'] and


b[1][1]['text'] and b[1][2]['text'] and b[2][0]['text'] and b[2][1]['text'] and b[2][2]['text'] !=
'':

stop_game = True

winner = messagebox.showinfo("tie", "Tie")

break

# Design window

root = Tk()

root.title("Tic Tac Toe")

root.resizable(0,0)

b = [[0,0,0],
[0,0,0],

[0,0,0]]

for i in range(3):

for j in range(3):

b[i][j] = Button(height = 2, width = 4, font = ("Helvetica","20"),

command = lambda r = i, c = j : clicked(r,c))

b[i][j].grid(row = i, column = j)

mainloop()

Output:
Result:

The program to create GUI board 3x3 board game with buttons was successfully
executed for Tic-tac-toe game

Ex. No. 4.3 Drawing Shapes with Canvas

AIM :
To write a python program to create canvas in GUI program and draw simple shapes such
as rectangles, circles, and lines.
ALGORITHM:
In this program we do some drawing. Drawing in Tkinter is done on the Canvas widget.
Canvas is a high-level facility for doing graphics in Tkinter.
It can be used to create charts, custom widgets, or create games.
Import the module tkinter and it’s canva class to create the required shapes
Canvas Methods for shapes:
Canvas.create_oval(x1, y1, x2, y2, options = …): It is used to create a oval, pieslice
and chord.
Canvas.create_rectangle(x1, y1, x2, y2, options = …): It is used to create rectangle
and square.
Canvas.create_line(x1, y1, x2, y2, options = …) This is used to create an line.
Canvas.create_polygon(coordinates, options = …) THis is used to create any valid
shapes.

Class is used to show the working of functions that helps to creates different shapes.
Class parameters –

Data members used: master, canvas


Member functions used: create() method
Widgets used: Canvas
Tkinter method used:
Canvas.create_oval()
Canvas.create_rectangle()
Canvas.create_line ()
pack()
title()
geometry()

Source Code
# Imports each and every method and class of module tkinter
from tkinter import *
class Shape:
def __init__(self, master = None):
self.master = master
# Calls create method of class Shape
self.create()
def create(self):
# Creates a object of class canvas
# with the help of this we can create different shapes
self.canvas = Canvas(self.master)
# Creates a circle of diameter 80
self.canvas.create_oval(10, 10, 80, 80, outline = "black", fill = "white",
width = 2)
# Creates an ellipse with horizontal diameter
# of 210 and vertical diameter of 80
self.canvas.create_oval(110, 10, 210, 80, outline = "red", fill = "green",
width = 2)
# Creates a rectangle of 50x60 (heightxwidth)
self.canvas.create_rectangle(230, 10,320, 60,outline = "black", fill =
"blue",width = 2)

# Creates an line
self.canvas.create_line(30, 200, 90, 100, fill = "red", width = 2)
# Pack the canvas to the main window and make it expandable
self.canvas.pack(fill = BOTH, expand = 1)
if __name__ == "__main__":
# object of class Tk, responsible for creating
# a tkinter toplevel window
master = Tk()
shape = Shape(master)
# Sets the title to Shapes
master.title("Shapes")
# Sets the geometry and position
# of window on the screen
master.geometry("330x220 + 300 + 300")
# Infinite loop breaks only by interrupt
mainloop()
OUTPUT:

Result: Thus the program is executed successfully.

Ex.No. 4.4 GUI Form Creation with Tkinter Event Handling


Aim:
To create a GUI form program that includes various widgets and implement event
handling Concepts. Also, Create a drop-down menu that allows users to select different
font styles for text display.

Algorithm:
Step 1: Start by importing the Tk class from the tkinter module. This class is used to create
the main application window.

Step 2: A function named clicked is defined. This function will be called when the "Submit"
button is clicked. It retrieves the text entered in the Entry widgets for name, department,
and year, concatenates them with appropriate labels, and sets the resulting text to the
display Label widget. Additionally, it changes the font of the display based on the option
selected from the dropdown menu.
Step 3: Create Main Window: An instance of the Tk class is created, representing the main
application window. The title of the window is set to "GUI Form" and its size is defined as
200x200 pixels.

Step 4: Define Variables: Two variables Name and choosen are defined. These variables
will be associated with StringVar and StringVar objects respectively.

Step 5: Create Widgets:


Labels: Labels for "DETAILS", "Name:", "Year:", "Dept:", and "Font" are created
and placed using the grid() method to organize them in rows and columns.
Entry Widgets: Entry widgets for entering the name, year, and department are
created and placed adjacent to their respective labels using the grid() method.
OptionMenu Widget: An OptionMenu widget is created to select the font. The font
options are provided as a dropdown menu. The default option is set to "select".
Button Widget: A button labeled "Submit" is created. When clicked, it will call the
clicked() function.
Display Label Widget: A Label widget named display is created to display the
entered details. Initially, it displays placeholders for Name, Department, and Year.
Step 6: Mainloop: The mainloop() method is called on the Tk instance to start the event
loop. This keeps the application running and responsive to user interactions un1til the
window is closed.
Program:
from tkinter import *
def clicked():
display.config(text = "Name:" + name_e.get() + "\nDept:" + dept_e.get() + "\nYear:" +
year_e.get())
display.config(font = choosen.get())
root = Tk()
root.title("GUI Form")
root.geometry("200x200")
Name = StringVar()
details = Label(root, text = "DETAILS")
details.grid(row = 0, column = 0, columnspan = 2)
name = Label(root, text = "Name:")
name.grid(row = 1, column = 0)
name_e = Entry(root)
name_e.grid(row = 1, column = 1)
year = Label(root, text = "Year:")
year.grid(row = 2, column = 0)
year_e = Entry(root)
year_e.grid(row = 2, column = 1)
dept = Label(root, text = "Dept:")
dept.grid(row = 3, column = 0)
dept_e = Entry(root)
dept_e.grid(row = 3, column = 1)
font = Label(root, text = "Font")
font.grid(row = 4, column = 0)
options = ['Arial', 'Helvetica', 'Times']
choosen = StringVar()
choosen.set('select')
drop = OptionMenu(root , choosen , *options)
drop.grid(row = 4, column = 1)
submit = Button(root, text = "Submit", command = clicked)
submit.grid(row = 5, column = 0, columnspan = 2)
display = Label(root, text = 'Name:\nDept:\nYear:')
display.grid(row = 8, column = 0, columnspan = 2)
mainloop()
OUTPUT:
Result: Thus the program is executed successfully.

You might also like