Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Jcs2201-Python Programming Unit-V Notes

The document covers file operations in Python, detailing how to open, read, write, and append to files, as well as the differences between binary and text files. It also discusses error types and exception handling, including built-in and user-defined exceptions, and provides examples of handling exceptions using try-except blocks. Additionally, it explains the importance of managing resources by closing files after operations and outlines various access modes for file handling.

Uploaded by

nandhakumars982
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Jcs2201-Python Programming Unit-V Notes

The document covers file operations in Python, detailing how to open, read, write, and append to files, as well as the differences between binary and text files. It also discusses error types and exception handling, including built-in and user-defined exceptions, and provides examples of handling exceptions using try-except blocks. Additionally, it explains the importance of managing resources by closing files after operations and outlines various access modes for file handling.

Uploaded by

nandhakumars982
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

FILES, EXCEPTIONS AND GUI

Files: Basic file operations and access methods. Errors and Exceptions: Syntax Errors, Exception types, Handling
Exceptions, Raising Exceptions, Simple graphics: simple 2D drawing shapes and coloring. GUI using Tkinter

Files:
 Files are named locations on disk to store related information. They are used to permanently store data in a non-
volatile memory (e.g. hard disk).
 To read from or write to a file, first open the file. When read/write operation is done, file needs to be closed so that
the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following
order:
 Open a file
 Read or write operation
 Close the file

Types Of Files in Python:


There are two types of files in Python. They are:
 Binary file
 Text file
Binary File:
A binary file is a file stored in binary format. A binary file is computer/machine readable but not human-readable because
all the binary files will be encoded in the binary format. All executable programs are stored in binary files, as are most numeric
data files. The term "binary file" is often used as a term meaning "non-text file". A binary file always needs a matching software to
read or write it.
Examples of binary file formats:

 Images : jpg, png, gif


 Videos : mp4
 Audio : mp3, wav, wma
 Documents : pdf, doc, xls, ppt, docx
 Archive : zip, rar
 Database : mdb, accde, frm, sqlite
 Executable : exe

Text files:
A text file is usually considered as sequence of lines. Line is a sequence of characters (ASCII), stored on permanent non-
volatile memory (e.g. hard disk). In text file, each line is terminated by a special character, known as End of Line (EOL). Text files
are stored in human readable form. Text file can be viewed or edited in any text editor.
Examples of text file formats:

 Web standards: html, xml, css, json


 Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh
 Documents: txt
 Configuration: ini, cfg
 Tabular data: csv, tsv

Opening or Creating a New File in Python:


All files must first be opened before doing any operation like read or write. Python has a built-in function OPEN() to open
a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. The method open()
is used to open an existing file or creating a new file. The syntax for using open() method is:
Syntax:
file_object = OPEN(“file_name”, “access_mode”)
- file_object is the variable to add the file object.
- file_name is the name of the file to access.
- access_mode is the mode in which the file has to be opened (read, write, append), which is optional and default file access
mode is read (r).
Example
To open the file in python:
f = open("test.txt") (or) f = open("test.txt", ‘r’) # open file in current directory
f = open("C:/Python33/README.txt") (or) f = open("C:/Python33/README.txt", ‘r’) # specifying full path

There are three different access modes are available in python:


• Read mode: is created only for reading and the pointer will be at the beginning of the file.
• Write mode: is used for overwriting the information on existing file.
• Append mode: is same as write mode, but instead of over writing, appends the information at the end of file.

Access modes in Text Files:


• ‘r' – Read Mode is used only to read data from the file.
• ‘w' – Write Mode is used to write/modify data into the file. It overwrites the existing data in the file.
• ‘a' – Append Mode is used to append data at the end of the file.
• ‘r+' – Read or Write Mode is used to write or read the data from the same file.
• ‘a+' – Append or Read Mode is used to read data from the file or append the data into the same file.
Access modes in Binary Files:
• ‘wb’ – Open a file in write only mode in the binary format.
• ‘rb’ – Open a file in read-only mode in the binary format.
• ‘ab’ – Open a file in append only mode in the binary format.
• ‘rb+’ – Open a file in read and write only mode in the binary format.
• ‘ab+’ – Open a file in append and read-only mode in the binary format.

Example1:
str= "This is a String in Python"
fp = open( ‘fil1.txt’,"w+")
fp.write(str)
fp.close()
print(fp.closed)
Reading Information from a File:
To read a file, open the file in read mode. There are three ways in which we can read the files in python.
 read([n])
 readline([n])
 readlines() – returns all lines to a list. Here, n is the number of bytes to be read.
Example 2:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.read(5))

Output: Hello
Here the file test.txt is opened in read-only mode and fp.read(5) method reads the first 5 characters of the file.

Example 3:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.read())
Output:
Hello World
Hello Python
Good Morning
How are you.
Here no argument is given inside the read() function. Hence it will read all the content present inside the file.

Example 4:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readline(2))
Output: He
This function returns the first 2 characters of the next line.
Example 5:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readline())
Output: Hello World
This function read the content of the file on a line by line basis.

Example 6:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readlines())
Output: [‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
This function reads all the lines present inside the text file including the newline characters.

Example 7:
Reading specific line from a File:
line_number = 4
fp = open(“C:/Documents/Python/test.txt”, ’r’)
currentline = 1
for line in fp:
if(currentline == line_number):
print(line)
break
currentline = currentline +1
Output: How are You
In the above example, the 4th line is read from the ‘test.txt’ file using “for loop”.

Example 8:
Reading the entire file:
filename = “C:/Documents/Python/test.txt”
f = open(filename, ‘r’)
filedata = f.read()
print(filedata)
Output:
Hello World
Hello Python
Good Morning
How are You

Write to a Python File:


In order to write data into a file, open the file in write mode. Two methods for writing data into a file:
– write(string)
– writelines(list)

Example 1:
f = open(“C:/Documents/Python/test.txt”, “w”)
f.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’ file

Example 2:
mf = open(“C:/Documents/Python/test.txt”, “w”)
mf.write(“Hello World\n”)
mf.write(“Hello Python”)
The first line will be ‘Hello World’ and as \n character is mentioned, the cursor will move to the next line of the file and then write
‘Hello Python’. If \n character is not mentioned, then the data will be written continuously in the text file like ‘Hello World Hello
Python’

Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
f = open(“C:/Documents/Python/test.txt”, “w”)
f.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously
Append in a Python File:
To append data into a file open the file in ‘a+’ mode to have access to both append and write modes.

Example 1:
m = open(“C:/Documents/Python/test.txt”, “a+”)
m.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file

Example 2:
f= open(“C:/Documents/Python/test.txt”, “a+”)
f.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new line.

Exception Handling
Errors
Errors or mistake in a program is often referred to as bugs. Debugging is the process of finding and eliminating
errors. Errors can be classified into three major categories
1. Syntax errors
2. Runtime errors
3. Logical errors
Syntax errors, also known as parsing errors are identified by Python while parsing the program, It displays error message
and exit without continuing execution process. They are similar to spelling mistakes or grammar mistakes. Some common
Python syntax errors include:
 leaving out a keyword
 putting a keyword in the wrong place
 leaving out a symbol, such as a colon, comma or brackets
 misspelling a keyword
 incorrect indentation
 empty block
Logical errors occur due to mistake in program’s logic. Here program runs without any error messages, but produces an
incorrect result. These errors are difficult to fix. Here are some examples of mistakes which lead to logical errors
 using the wrong variable name
 indenting a block to the wrong level
 using integer division instead of floating-point division
 getting operator precedence wrong
 making a mistake in a Boolean expression
 off-by-one, and other numerical errors
Runtime error is an exception that occurs during the execution of a program. Examples of Python runtime errors are:
 division by zero
 performing an operation on incompatible types
 using an identifier which has not been defined
 accessing a list element, dictionary value or object attribute which doesn’t exist
 trying to access a file which doesn't exist
TYPES OF EXCEPTION
There are two types of Exception:
 Built-in Exception
 User Defined Exception
i) Built-in Exception
There are some built-in exceptions which cannot be changed. The Syntax for Built-in Exception is:
except Exception_Name:
An Exception is an event which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.
If a python script encounters a situation it cannot cope up, it raises an exception. There are four blocks which help to handle the
exception. They are :
 try block
 except statement
 else block
 finally block

DEFAULT EXCEPTION HANDLER


Consider the following examples in which syntax is correct (as per the Python statement), but it causes an error.
Example 1.
>>>3/0
Name of Error will be ZeroDivisionError
And the reason for the error is division by zero
Example 2
>>> list1=[2, 3, 4, 5, 6] >>>list1[5]
Name of Error is :IndexError
Reason of Error is : list index out of range
Example 3. >>>x+3
Name of Error is : Name Error
Reason of Error is : name 'x' is not defined"
Example 4. >>>int('22.5') Name of Error is : ValueError
Reason of error is : invalid literal for int() with base 10: '22.5'
Example 5. >>> '2'*'3'
Error name is :TypeError
Reason of Error is : Raised when an operation or function is attempted that is invalid for the specified data type,
can't multiply sequence by non-int of type 'str'.
IOError Raised - when an input/ output operation fails, such as the print statement or the open() function when trying to
open a file that does not exist.
ArithmeticError - Base class for all errors that occur for numeric calculation.
RuntimeError - Raised when a generated error does not fall into any category

Mechanisms for handling exception in Python:


 basic 'try' and 'except' block
 ‘try’ and multiple ‘except’ block
 ‘try’ and ‘else’ clause
 ‘try’ ‘except’ and ‘finally’ clause
 raise exception
 nested exception
The try statement works as follows.
 First, the try clause (the statement(s) between the try and except keywords) is executed.
 If no exception occurs, the except clause is skipped and execution of the try statement is finished.
 If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type
matches the exception named after the except keyword, the except clause is executed, and then execution
continues after the try statement.
 If an exception occurs which does not match the exception named in the except clause, it is passed on to outer
try statements; if no handler is found, it is an unhandled exception and execution stops with a message.
1. Basic 'try' and 'except' block:
The simplest way to handle exception is with “try-except” block. Exceptions that are caught in try
blocks are handled in except blocks. If an error is encountered, a try block code execution is stopped and control
transferred down to except block.
Syntax:
try:
# statements
break
except ErrorName:
#handler code

Example:
(a,b) = (5,0)
try:
z=x/y
except ZeroDivisionError:
Print (“Divide by Zero”)
Output: Divide by Zero
`Exceptions come in different types, and the types printed as part of the message: the type in the example
is ZeroDivisionError which occurs due to division by 0. The string printed as the exception type is the name of the
built-in exception that occurred.

2. ‘try’ and multiple ‘except’ block


A try statement may have more than one except clause.

3. ‘try’ ….'else' clause:


Python goes a step further and provides an 'else' clause in exception handling. The code inside
the 'else' block is executed if the code inside 'try' runs without any exceptions.

def divide (x, y):


try:
result=x/y
except ZeroDivisionError:
print(“Divide by zero error”)
else:
print(“Result=”, result)
divide (3, 2)
divide (3,0)

4. ‘try’ ‘except’ and ‘finally’ clause:


Sometimes exceptions may or may not be raised, or handled. Irrespective of both of these, still want
to execute some code, such codes are written in finally block. The 'finally' clause is an optional clause that is
intended to define clean-up actions. The 'finally' clause is executed no matter what, whether an exception has
been raised or not.
5. “raise” exception: To throw (or raise) an exception, use the raise keyword
try:
x = -1
if x < 0:
raise Exception("Number is below zero")

6.Nesed try-except block:


If a try block is written inside another try block, then it is called as nested. The code having higher risk must be defined in
the innermost try block. If there is any exception raised by the innermost try block, then it will be handled by the innermost except
block. If the innermost except block is not able to handle the error then except block defined outside the inner try block will handle
the exception.

Example:

7. Default exception:

User-Defined Exception in Python: In this example, we will illustrate how user-defined exceptions can be used in a
program to raise and catch errors. This program will ask the user to enter a number until they guess a stored number
correctly. To help them figure it out, hint is provided whether their guess is greater than or less than the stored number.
number = 10
while True:
try:
num = int(input("Enter a number: "))
if num < number:
raise ValueTooSmallError
elif num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.")

Output:

Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.

1. Write a python program to read a file which raises an exception


Assume test.txt is not created in the computer and the following program is executed which raises an exception.

2. Write python program to count number of words in a file. (Using Exception Handling)

try:
filename = ‘T.txt'
textfile = open(filename, ‘r’)
print(“The number of words are: “ + len(textfile.split(“ “)))
textfile.close()
except IOError:
print (‘Cannot open file %s for reading’, % filename)
import sys
sys.exit(0)
Output
The number of word are : 20

3. Write python program to count number of lines, words and characters in a text file.
count_line=0
count_word=0
count_character=0
f=open("sample.txt","r") for line in f:
words=line.split()
count_line +=1
count_word +=len(words)
count_character +=len(line)
print('No. of lines:', count_line)
print('No. of words:', count_word)
print('No. of characters:', count_character)
f.close()

4. Write Python program to copy a content of one file to another.

rf=open (‘testfile1.txt’, ‘r’)


try:
r=rf. read()
wf=open(‘testfile2txt’, ‘w’)
try:
wf. write(r)
finally:
wf.close()
finally:
rf.close()

GRAPHICS PROGRAMMING IN PYTHON

There are many Python packages that can be used to create graphics and GUI’s. Two graphics modules, called turtle and
tkinter, come as a part of Python’s standard library. tkinter is primarily designed for creating GUI’s. In fact, IDLE is built using
tkinter. However, turtle module is primarily used as a simple graphics package but can also be used to create simple GUI’s. The turtle
module is an implementation of turtle graphics and uses tkinter for the creation of the underlying graphics

Importing turtle graphics:


In order to start using turtle graphics, import the turtle module. Start Python/IDLE and type the following:
>>> import turtle as t
This imports the turtle module using the identifier t. By importing the module this way, the methods within the module can be
accessed using t.
Commands to change the turtle’s heading and draw a square box:
>>> t.left(90)
>>> t.fd(100)
>>> t.left(90)
>>> t.fd(100)
>>> t.left(90)
>>> t.fd(100)

Using penup() and setposition() to move the turtle without making a line
>>> t.penup()
>>> t.setposition(100, -100)
>>> t.pendown()
>>> t.fd(130)
Result of moving the turtle without drawing a line and then, once at the new location, drawing a line.

>>> t.reset() # Remove previous drawings and reset turtle.


>>> t.circle(100) # Draw circle counterclockwise with radius 100.
>>> t.circle(-50) # Draw circle clockwise with radius 50.

Write a python program using turtle to draw different 2D drawing shapes and color them.
import turtle
def draw_circle(radius, color):
turtle.begin_fill()
turtle.color(color)
turtle.circle(radius)
turtle.end_fill()

def draw_square(length, color):


turtle.begin_fill()
turtle.color(color)
for i in range(4):
turtle.forward(length)
turtle.right(90)
turtle.end_fill()

def draw_rectangle(length, breadth, color):


turtle.begin_fill()
turtle.color(color)
for i in range(2):
turtle.forward(length)
turtle.left(90)
turtle.forward(breadth)
turtle.left(90)
turtle.end_fill()

def draw_triangle(length, color):


turtle.begin_fill()
turtle.color(color)
for i in range(3):
turtle.forward(length)
turtle.left(120)
turtle.end_fill()

radius = 50
length = 100
breadth = 200
turtle.speed(2)
draw_circle(radius, "magenta")
draw_square(length, "red")
turtle.penup()
turtle.goto(150, 0)
turtle.pendown()
draw_rectangle(length, breadth, "green")
draw_triangle(length, "black")
t urtle.exitonclick()

TKINTER (GUI TOOLKIT ):


GUI library given with the python programming langauage is Tkinter. GUI applications using widgets can be created
easily and quickly using Tkinter. Tkinter is the Python's most commonly used standard GUI toolkit package. Since Tkinter
is the Python interface to Tk (Tea Kay), it can be pronounced as Tea-Kay-inter. i.e tkinter = t k inter
To create Tkinter app in Python:
1. In Python 2.x, import Tkinter while in Python 3.x, import tkinter
2. Create a main window (container) for all GUI elements.
3. Add widgets to the main window like buttons, labels, check button, etc.
4. Apply event triggers to the widgets to define how they respond to user interactions.
To create a main window Tk():
Tk (screenname=None, baseName=None, className= ‘Tk’, useTk=1)
- To change window name change className
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.
Creating GUI using tkinter:
import Tkinter
tp=Tkinter.Tk()
# widgets are added here
tp.mainloop()

tkinter window

Here are some of the widgets available:

Widget Class Description


Label A widget used to display text on the screen
Button A button that can contain text and can perform an action when clicked
Entry A text entry widget that allows only a single line of text
Text A text entry widget that allows multiline text entry
Frame A rectangular region used to group related widgets or provide padding between widgets

S. Options Description
No
1 anchor Specifies the exact position of the text. The default value is CENTER, which is used
to center the text within the specified space.
2 bg The background color displayed behind the widget.
3 bitmap To set the bitmap to the graphical object specified so that, the label can represent
the graphics instead of text.
4 bd Represents the width of the border. The default is 2 pixels.
5 cursor The mouse pointer will be changed to the type of the cursor specified, i.e., arrow,
dot, etc.
6 font font type of the text written inside the widget.
7 fg The foreground color of the text written inside the widget.
8 height Specifies the height of the widget.
9 image The image that is to be shown as the label.
10 justify To represent the orientation of the text if the text contains multiple lines. It can be
set to LEFT, RIGHT, and CENTER justification.
11 padx Horizontal padding of the text. The default value is 1.
12 pady Vertical padding of the text. The default value is 1.
13 relief The type of the border. The default value is FLAT.
14 text Set to the string variable which contain one or more line of text.
15 textvariable The text written inside the widget is set to the control variable StringVar so that it
can be accessed and changed accordingly.
16 underline To display a line under the specified letter of the text. Set this option to the number
of the letter under which the line will be displayed.
17 width The width of the widget specified as number of characters.
18 wraplength Instead of having only one line as the label text, can break it to the number of lines
where each line has the number of characters specified to this option.

Tkinter Widgets:

1. Label
Syntax:
W=Label (master, option=value)
master is the parameter to represent parent window

Example:
import Tkinter as tk
m=tk.Tk()
label = tk.Label(m, text="Hello, Tkinter",fg="white",bg="black" width=10,height=1)
m.mainloop()

2.Button: widgets used to display clickable buttons.


Syntax:
Button (master, option = value)
Parameters:
 master: This argument is used to represent or declare the root or parent window.
 option: There are different values for options in the button widgets such as activebackground
color, activeforeground color, bg, font, image, width, height, command, etc

Example:
import Tkinter as tk
m=tk.Tk()
but = tk. Button(m, text="Click me!", width=25,height=5, bg=”blue”, fg=”yellow”)
m.mainloop()
3. Input With Entry Widgets: displays text box where user can type texts. Creating and styling an Entry widget works
pretty much exactly like Label and Button widgets.

import Tkinter as tk
m=tk.Tk()
label = tk.Label(m, text="Name")
entry=tk.Entry()
label.pack()
entry.pack()
m.mainloop()

>>> entry.insert (0, “Python”)

>>> entry.insert (0, “Real”)


The widget text now reads Real Python

4. Check button: used to store or record status like on or off, true or false, etc., which means these are like buttons but used when
the user wants to choose between two different values or status. In this, the user can select more than one checkbox. Let us see an
example of how this button works. Options can be like the title for giving the title to the widget, activebackground, and
activeforeground for setting back and foreground color, bg for setting up the background color, command, font, image, etc.
Syntax:
w=CheckButton (master, option=value)

Example:
from tkinter import *
root = Tk()
v1 = IntVar()
Checkbutton(root, text='Python',width =25, variable=v1).grid(row=0, sticky=S)
v2 = IntVar()
Checkbutton(root, text='Unix',width =25, variable=v2).grid(row=1, sticky=S)
v3 = IntVar()
Checkbutton(root, text='Perl',width =25, variable=v3).grid(row=2, sticky=S)
mainloop()
Output:
5. RadioButton: similar to the checkbutton, but this widget is used when the user is given many different options
but is asked to select only one among the options. The radiobutton widget must be associated with the same
variable, and each symbolizes a single value.
Syntax:
RadioButton (master, option = values)
Options are the same as for checkbuttons.

Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='male',width =25, variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='female',width =25, variable=v, value=2).pack(anchor=W)
Radiobutton(root, text='others',width =25, variable=v, value=3).pack(anchor=W)
mainloop()
Output:

6. MenuButton is associated with a menu widget and displays the selected option when user clicks on it.
MenuButton is part of a dropdown menu that is always present on the window.
Syntax:
MenuButton (master, option = value)
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")
menubutton = Menubutton(root, text = "File", width = 35)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_checkbutton(label = "New file", variable=IntVar())
menubutton.menu.add_checkbutton(label = "Save", variable = IntVar())
menubutton.menu.add_checkbutton(label = "Save as",variable = IntVar())
menubutton.pack()
root.mainloop()
Output:
In the above example, when “File” is clicked a dropdown menu appears as “New file”, “Save”, and “Save as” else
“File” is only on the window.

7. Frame: is a rectangular region on the screen to implement complex widgets and to organize a group of
widgets.

Syntax: w= Frame( master, options)

Example1
import Tkinter as tk
m=tk.Tk()
frme1 = tk.Frame()
lbl1=tk.Label(frme1, text=” I’m in Frame A”
lbl1.pack()
frme2= tk.Frame()
lbl2=tk.Label(frme2, text=” I’m in Frame B”
lbl2.pack()
frme2.pack()
frme1.pack()
m.mainloop()
Output:

Example2
import Tkinter as tk
m=tk.Tk()
frme1 = tk.Frame(m, width=200, height=100, bg=”red”)
frme1.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frme2 = tk.Frame(m, width=100, height=100, bg=”yellow”)
frme2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frme3 = tk.Frame(m, width=50, height=100, bg=”blue”)
frme3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
m.mainloop()
1. Create a simple registration form using Tkinter
import tkinter as tk
from tkinter import messagebox
def submit_form():
username = entry_username.get()
password = entry_password.get()
messagebox.showinfo("Registration Successful", f"Welcome, {username}!")
root = tk.Tk()
root.title("Registration Form")
label_username = tk.Label(root, text="Username:")
label_username.grid(row=0, column=0, padx=10, pady=10)
entry_username = tk.Entry(root)
entry_username.grid(row=0, column=1, padx=10, pady=10)
label_password = tk.Label(root, text="Password:")
label_password.grid(row=1, column=0, padx=10, pady=10)
entry_password = tk.Entry(root, show="")
entry_password.grid(row=1, column=1, padx=10, pady=10)
submit_button = tk.Button(root, text="Submit", command = submit_form)
submit_button.grid(row=2, column=0, columnspan=2, pady=10)
root.mainloop()

You might also like