0% found this document useful (0 votes)
4 views21 pages

Tkinter GUI Programming Guide

The document provides an overview of creating GUI applications in Python using the tkinter library, detailing the steps to set up a tkinter app and describing various widgets like Button, CheckButton, Entry, and Menu with examples. It also covers SQL operations using pyodbc for connecting to an MS SQL database, including select, insert, update, and delete statements. Additionally, it introduces MongoDB integration with Python using PyMongo, explaining how to create databases, collections, and perform CRUD operations.

Uploaded by

nikitapandav063
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)
4 views21 pages

Tkinter GUI Programming Guide

The document provides an overview of creating GUI applications in Python using the tkinter library, detailing the steps to set up a tkinter app and describing various widgets like Button, CheckButton, Entry, and Menu with examples. It also covers SQL operations using pyodbc for connecting to an MS SQL database, including select, insert, update, and delete statements. Additionally, it introduces MongoDB integration with Python using PyMongo, explaining how to create databases, collections, and perform CRUD operations.

Uploaded by

nikitapandav063
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

Assignment on GUI

Prerequisite:
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
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the Python code. Note that the
name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.

import tkinter

There are two main methods used which the user needs to remember while creating the
Python application with GUI.
1. 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=[Link]() where m is the name of the main window object
2. 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.
[Link]()
Example-

import tkinter
m = [Link]()
'''
widgets are added here
'''
[Link]()
There are a number of widgets which you can put in your tkinter application. Some of the
major widgets are explained below:
1. Button:To add a button in your application, this widget is used.
The general syntax is:

w=Button(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
• 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.
• 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.

Code:

import tkinter as tk
r = [Link]()
[Link]('Counting Seconds')
button = [Link](r, text='Stop', width=25, command=[Link])
[Link]()
[Link]()

Output:

2. CheckButton: To select any number of options by displaying a number of


options to a user as toggle buttons. The general syntax is:
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• 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 color.
• command: to call a function.
• font:
to set the font on the button label.
• image: to set the image on the widget.

Code :
from tkinter import *
master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()
Output:

3. Entry:It is used to input the single line text entry from the user.. For multi-line
text input, Text widget is used.
The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• 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.
Code:
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
[Link](row=0, column=1)
[Link](row=1, column=1)
mainloop()
Output:

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


The general syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
• 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 color.
• command: to call a function.
• font:
to set the font on the button label.
• image: to set the image on the widget.
Code:
from tkinter import *
root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=[Link])
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

Output:
Assignments : -

1. Write GUI program in Python for Registration.


2. Write GUI program in Python for Login.
3. Write GUI program in Python which contains menu and using menu
open different windows.
4. Write GUI program in Python for Calculator.
5. Write GUI program in Python for Marksheet.

Signature of Instructor Date :

Assignment Evaluation
1. Incomplete 2. Late Complete 3. Needs Improvement
[Link] [Link] Done
Assignment on SQL & Mango DB Database

Prerequisite:
We already have MS SQL server and python Setup installed on machine.
Get started with MSSQL Connection String

import pyodbc
conn = [Link]("DRIVER={ ServerName };SERVER=server Name;
database= MSQLDatabase;trusted_connection=yes;UID= username;PWD=
password)
cursor = [Link]()

here, first import pyodbc


then create conn object for SQL connection string. Using [Link] we
can create connection string using following parameters,

DRIVER={ ServerName } - Here DRIVER means your SQL server


SERVER= server Name -SERVER means SQL Server Name
database= MSQLDatabase -database means Database Name

if we use SQL server Authentication in SQL server then we add following in


connection string.

UID= username - User Name


PWD= password - Password

Python SQL Select Statement-


we show how to use the select statement to select records from a Table.

The following are a few of the operations we can do on SQL Server but are not limited to
them.

Before that you have to create one Database in Your MS SQL server using

SSMS( SQL SERVER MANAGEMENT SYSTEM )


# Example
import pyodbc
conn = [Link]("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Database=SQLTutorial;"
"Trusted_Connection=yes;")

cursor = [Link]()
[Link]('SELECT * FROM CustomerSale')

for row in cursor:


print('row = %r' % (row,))

First, we imported or selected data from the Customer Sales table


present in SQL Tutorial Database.

cursor = [Link]('SELECT * FROM CustomerSale')

Next, we used the For loop to iterate each row present in the Customer
Sales table. Within the For Loop, we used the print statement to print
rows.

for row in cursor:


print('row = %r' % (row,))

Python SQL Insert Statement-


# Example
import pyodbc
conn = [Link]("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Database=SQLTutorial;"
"Trusted_Connection=yes;")

cursor = [Link]()
[Link]('Insert into CustomerSale ( DepartmentID, Name,
GroupName ) values(?,?,?)",DepartmentID, Name, GroupName')
[Link]()
Python SQL Update Statement-
# Example
import pyodbc
conn = [Link]("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Database=SQLTutorial;"
"Trusted_Connection=yes;")

cursor = [Link]()
[Link]('Update CustomerSale set Name=? where DepartmentID=? ‘,(
‘Ramesh’,’6’))
[Link]()

Python SQL delete Statement-


# Example
import pyodbc
conn = [Link]("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Database=SQLTutorial;"
"Trusted_Connection=yes;")

cursor = [Link]()
[Link]('delete from CustomerSale where DepartmentID=? ‘,( ’6’))
[Link]()

***************************Mongo dB with Python***************************

MongoDB stores data in JSON-like documents, which makes the database very
flexible and scalable.

To be able to experiment with the code examples in this tutorial, you will need
access to a MongoDB database.

You can download a free MongoDB database at [Link]

PyMongo
Python needs a MongoDB driver to access the MongoDB database.

In this tutorial we will use the MongoDB driver "PyMongo".


We recommend that you use PIP to install "PyMongo".

PIP is most likely already installed in your Python environment.

Creating a Database
To create a database in MongoDB, start by creating a MongoClient object, then
specify a connection URL with the correct ip address and the name of the database
you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.

Example
Create a database called "mydatabase":
import pymongo

myclient = [Link]("mongodb://localhost:27017/")

mydb = myclient["mydatabase"]

Check if Database Exists


You can check if a database exist by listing all databases in you system:
dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")

Creating a Collection
To create a collection in MongoDB, use database object and specify the name
of the collection you want to create.

MongoDB will create the collection if it does not exist.

Example
Create a collection called "customers":
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Insert Into Collection
To insert a record, or document as it is called in MongoDB, into a collection, we
use the insert_one() method.

The first parameter of the insert_one() method is a dictionary containing the


name(s) and value(s) of each field in the document you want to insert.

Example
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)

Update Collection
You can update a record, or document as it is called in MongoDB, by using
the update_one() method.

The first parameter of the update_one() method is a query object defining which
document to update.

The second parameter is an object defining the new values of the document.

Example
Change the address from "Valley 345" to "Canyon 123":
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Valley 345" }


newvalues = { "$set": { "address": "Canyon 123" } }

mycol.update_one(myquery, newvalues)

#print "customers" after the update:


for x in [Link]():
print(x)
Update Many
To update all documents that meets the criteria of the query, use
the update_many() method.

Example
Update all documents where the address starts with the letter "S":
import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$regex": "^S" } }


newvalues = { "$set": { "name": "Minnie" } }

x = mycol.update_many(myquery, newvalues)

print(x.modified_count, "documents updated.")

Delete Document
To delete one document, we use the delete_one() method.

The first parameter of the delete_one() method is a query object defining which
document to delete.

Example
Delete the document with the address "Mountain 21":

import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Mountain 21" }

mycol.delete_one(myquery)
Delete Many Documents
To delete more than one document, use the delete_many() method.

The first parameter of the delete_many() method is a query object defining which
documents to delete.

Example
Delete all documents were the address starts with the letter S:

import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": {"$regex": "^S"} }

x = mycol.delete_many(myquery)

print(x.deleted_count, " documents deleted.")

Delete All Documents in a Collection


To delete all documents in a collection, pass an empty query object to
the delete_many() method:

Example
Delete all documents in the "customers" collection:

import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.delete_many({})

print(x.deleted_count, " documents deleted.")


Find One
To select data from a collection in MongoDB, we can use the find_one() method.

The find_one() method returns the first occurrence in the selection.

Example
Find the first document in the customers collection:

import pymongo
myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.find_one()

print(x)

Find All
To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we use
an empty query object, which selects all documents in the collection.

Example
Return all documents in the "customers" collection, and print each document:

import pymongo

myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in [Link]():
print(x)
Return Only Some Fields
The second parameter of the find() method is an object describing which fields to
include in the result.
This parameter is optional, and if omitted, all fields will be included in the result.
Example
Return only the names and addresses, not the _ids:

import pymongo

myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in [Link]({},{ "_id": 0, "name": 1, "address": 1 }):


print(x)

Assignments : -
First Create a Database “StudInfo” with Tables (studDetails,ClassDetails)
And write All programme for SQL and Mongo DB also.
1. Write a Program to Insert Some Values in both Tables use(SQL and
MongoDB)
2. Write a program to Update Student Address,Birthdate etc. use(SQL and
MongoDB)
3. Write a program to delete Student details which have age between 16 to 20.
4. Write a Program to Search Student who have in Class ‘A’ and Name start
with ‘D’ also search student who have age 25 use(SQL and MongoDB)

Signature of Instructor Date :

Assignment Evaluation
1. Incomplete 2. Late Complete 3. Needs Improvement
1. Complete [Link] Done
Assignment 3 :

Prerequisite:
What is NumPy?
NumPy is a Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier transform,
and matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.

NumPy stands for Numerical Python.

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to
process.

NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.

The array object in NumPy is called ndarray, it provides a lot of supporting


functions that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources are
very important.

Why is NumPy Faster Than Lists?


NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.

Which Language is NumPy written in?


NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.

Install it using this command in Terminal:

C:\Users>pip install numpy

If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.

Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy

Now NumPy is imported and ready to use.

Example
import numpy
arr = [Link]([1, 2, 3, 4, 5])
print(arr)

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

Example
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

type(): This built-in Python function tells us the type of the object passed to it.
Like in above code it shows that arr is [Link] type.

To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:

import numpy as np
arr = [Link]((1, 2, 3, 4, 5))
print(arr)
Assignments : -

1. Write a NumPy program to convert a list of numeric values into a


one-dimensional NumPy array.
2. Write a Program to demonstrate Split functions in NumPy array.
3. Write a Program to demonstrate Slicing functions in NumPy array.
4. Write a Program to demonstrate ufunc functions in NumPy array.

Signature of Instructor Date :

Assignment Evaluation
1. Incomplete 2. Late Complete 3. Needs Improvement
4. Complete [Link] Done
Assignment 4 :

Prerequisite:

What is Pandas?
Pandas is a Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data
Analysis" and was created by Wes McKinney in 2008.

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical
theories.

Pandas can clean messy data sets, and make them readable and relevant.

Relevant data is very important in data science.

What Can Pandas Do?


Pandas gives you answers about the data. Like:

• Is there a correlation between two or more columns?


• What is average value?
• Max value?
• Min value?

Pandas are also able to delete rows that are not relevant, or contains wrong
values, like empty or NULL values. This is called cleaning the data.

Installation of Pandas
If you have Python and PIP already installed on a system, then installation of
Pandas is very easy.

Install it using this command:

C:\Users>pip install pandas

If this command fails, then use a python distribution that already has Pandas
installed like, Anaconda, Spyder etc.
What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array,
or a table with rows and columns.

Example
Create a simple Pandas DataFrame:

import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}

#load data into a DataFrame object:


df = [Link](data)

print(df)

Result
calories duration
0 420 50
1 380 40
2 390 45

Locate Row
As you can see from the result above, the DataFrame is like a table with rows and
columns.

Pandas use the loc attribute to return one or more specified row(s)

Example
Returen Row 0:

#refer to the row index:


print([Link][0])

Result
calories 420
duration 50
Name: 0, dtype: int64
Read CSV Files
A simple way to store big data sets is to use CSV files (comma separated files).

CSV files contains plain text and is a well know format that can be read by
everyone including Pandas.

In our examples we will be using a CSV file called '[Link]'.

Example
Load the CSV into a DataFrame:

import pandas as pd
df = pd.read_csv(r'D:\[Link]')
print(df.to_string())

max_rows
The number of rows returned is defined in Pandas option settings.

You can check your system's maximum rows with


the [Link].max_rows statement.

Example
Check the number of maximum returned rows:

import pandas as pd
print([Link].max_rows)

In my system the number is 60, which means that if the DataFrame contains more
than 60 rows, the print(df) statement will return only the headers and the first
and last 5 rows.

You can change the maximum rows number with the same statement.

import pandas as pd
[Link].max_rows = 9999
df = pd.read_csv('[Link]')
print(df)
Assignments : -

1. Write a Program to demonstrate DataFrames in Pandas


2. Write a Program to demonstrate Read CSV in Pandas
3. Write a Program to demonstrate Read JSON in Pandas
4. Write a Program to demonstrate Removing Duplicates in Pandas

Signature of Instructor Date :

Assignment Evaluation
1. Incomplete 2. Late Complete 3. Needs Improvement
4. Complete [Link] Done

You might also like