Python Modules and GUI In Python

Python module is a file consisting of python code. A module can define functions, classes and variables. A module can also include runnable code. Any Python source file can be used as a module by executing an import statement in some other Python source file.

Creating a module

To create a module save the code you want in a file with extension .py

Example-> def func(name):

                             print(name)

Save this program as my_module.py

 

Using a module

When using a function from a module, use the syntax: module_name.function_name.

Example->

import my_module

my_module.func(“Jasmin”)

output-> Jasmin

 

 

Example-> fruit = {

                   "name": "Apple",

  "colour": "red",

  "price": 30

}

Save this code as fruit_module.py

Import this module

import fruit_module

x= fruit_module.fruit[colour”]

print(x)

output-> red

 

Built-in module

Math module

Python provides several built-in modules which you can import wherever you want.

Example-> import math

                   print(math.pi)

output->  3.141592653589793

 

pi as whole can be imported into our initial code, rather than importing the whole module.

Example-> from math import pi

print(pi)

 

In the above code module math is not imported, rather just pi has been imported as a variable.

All the functions and constants can be imported using *.

 

Example-> from math import *

                   print(pi)

                   print(factorial(6))

          output-> 3.141592653589793

       720

 

Random module

This module is used to perform some action randomly such as getting random numbers, selecting random variable, etc.

random.random() is used to generate random float number between 0.0 to 1.0.

Example-> import random

print(random.random())

output-> 0.36451917373498566

 

random.randint() is used to generate random int number between given range.

Example-> import random

                   print(random.randint(1,60))

          output-> 45

 

random.randrange() method returns a randomly selected element from the range created by the start, stop and step arguments.

Example-> import random

print(random.randrange(1, 10))

          output-> 5

 

random.choice() method returns a randomly selected element from a non-empty sequence.

Example-> import random

print(random.choice('Hello'))

print(random.choice([1,2,5,7,6,4]))

output-> o

                 5

 

Itertools

Itertool is a module that provides various functions that work on iterators to produce more complex iterators..

count(start, step) This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default.

Example-> import itertools

for i in itertools.count(5, 10):

    if i == 35:

        break

    else:

        print(i, end =" ")

          ouput-> 5 15 25

cycle(iterable) This iterator prints all values in order from the passed container. It restarts printing from the beginning again when all elements are printed in a cyclic manner.

Example-> import itertools

count = 0

for i in itertools.cycle('AB'):

    if count > 7:

        break

    else:

        print(i, end = " ")

        count += 1

output-> A B A B A B A B

 

repeat(val, num) This iterator repeatedly prints the passed value infinite number of times. If the optional keyword num is mentioned, then it repeatedly prints num number of times.

Example-> import itertools 

print ("Printing the numbers repeatedly : ") 

print (list(itertools.repeat(25, 4)))

output-> Printing the numbers repeatedly :

       [25, 25, 25, 25]

 

Permutations() Permutations() is used to generate all possible permutations of an iterable.

Example-> from itertools import permutations

   

print ("All the permutations of the given string is:") 

print (list(permutations('AB')))

print()

print ("All the permutations of the given container is:") 

print(list(permutations(range(3), 2)))

output-> All the permutations of the given string is:

       [('A', 'B'), ('B', 'A')]

 

       All the permutations of the given container is:

       [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

 

Combinations() This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.

Example-> from itertools import combinations     

print ("All the combination of list in sorted order(without replacement) is:") 

print(list(combinations(['A', 2], 2)))

print()

output-> All the combination of list in sorted order(without replacement) is:

[('A', 2)]

 

islice(iterable, start, stop, step) This iterator selectively prints the values mentioned in its iterable container passed as argument.

Example-> import itertools

li = [2, 4, 5, 7, 8, 10, 20]

print ("The sliced list values are : ", end ="")

print (list(itertools.islice(li, 1, 6, 2)))

The sliced list values are : [4, 7, 10]

 

cmath module

Python has a built-in module that you can use for mathematical tasks for complex numbers. The methods in this module accepts int, float, and complex numbers.

The cmath module has a set of methods and constants.

cmath.cos(x) Returns the cosine of x

Example-> import cmath

#find the cosine of a complex number

print (cmath.cos(2 + 3j))

          output-> (-4.189625690968807-9.109227893755337j)

 

cmath.isclose() Checks whether two values are close, or not

Example-> import cmath

#compare the closeness of two complex values using relative tolerance

print(cmath.isclose(10+5j, 10.0+5j))

print(cmath.isclose(10+5j, 10.01+5j))

          output-> True

                          False

 

cmath.log(x[, base]) Returns the logarithm of x to the base

Example-> import cmath

print (cmath.log(1+ 1j))

print (cmath.log(1, 2.5))

          ouput-> (0.34657359027997264+0.7853981633974483j)

      0j

 

cmath.log10(x) Returns the base-10 logarithm of x

Example-> import cmath 

print (cmath.log10(2+ 3j))

print (cmath.log10(1+ 2j))

          output-> (0.5569716761534184+0.42682189085546657j)

       (0.3494850021680094+0.480828578784234j)

 

cmath.sqrt(x) Returns the square root of x

Example-> import cmath 

print (cmath.sqrt(2 + 3j))

print (cmath.sqrt(15))

          output-> (1.6741492280355401+0.8959774761298381j)

       (3.872983346207417+0j)

 

cmath.tan(x) Returns the tangent of x

Example-> import cmath 

print (cmath.tan(2 + 3j))

          output-> (-0.003764025641504249+1.00323862735361j)

 

Time module

Python has a module, “time” which has various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.

time() This function is used to count the number of seconds elapsed since the epoch.

gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds from epoch. If no seconds are mentioned, time is calculated till present.

Example-> import time

print ("Seconds elapsed since the epoch are : ",end="")

print (time.time())

print ("Time calculated acc. to given seconds is : ")

print (time.gmtime())

output-> Seconds elapsed since the epoch are :                                   1618063286.4975939

Time calculated acc. to given seconds is :

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=10, tm_hour=14, tm_min=1, tm_sec=26, tm_wday=5, tm_yday=100, tm_isdst=0)

 

sleep(sec) This method is used to hault the program execution for the time specified in the arguments.

 

Example-> import time

print ("Start Execution : ",end="")

print (time.ctime())

time.sleep(4)

print ("Stop Execution : ",end="")

print (time.ctime())

          output-> Start Execution : Sat Apr 10 14:04:35 2021

       Stop Execution : Sat Apr 10 14:04:39 2021

 

GUI

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method.

Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths. It’s cross-platform, so the same code works on Windows, macOS, and Linux.

 

 

To create a tkinter app:

Importing the module – tkinter

Create the main window (container)

Add any number of widgets to the main window

Apply the event Trigger on the widgets.

 

Importing tkinter is same as importing any other module in the Python code.

import tkinter

 

There are two main methods used which the user needs to remember while creating the Python application with GUI.

 

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

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

 

mainloop()

m.mainloop()

 

import tkinter

m = tkinter.Tk()

'''

widgets are added here

'''

m.mainloop()

 

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.

Example-> import tkinter as tk

r = tk.Tk()

r.title('Counting Seconds')

button = tk.Button(r, text='Stop', width=25, command=r.destroy)

button.pack()

r.mainloop()

output->https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-300x67.png

 

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)

Example-> 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-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-2.png

 

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

w=Entry(master, option=value)

Example-> 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)

e1.grid(row=0, column=1)

e2.grid(row=1, column=1)

mainloop()

          output-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-3.png

 

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

The general syntax is:

w = Listbox(master, option=value)

master is the parameter used to represent the parent window.

Example-> from tkinter import *

top = Tk()

Lb = Listbox(top)

Lb.insert(1, 'Python')

Lb.insert(2, 'Java')

Lb.insert(3, 'C++')

Lb.insert(4, 'Any other')

Lb.pack()

top.mainloop()

          output-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-6.png

 

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.

Example-> from tkinter import *

root = Tk()

menu = Menu(root)

root.config(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=root.quit)

helpmenu = Menu(menu)

menu.add_cascade(label='Help', menu=helpmenu)

helpmenu.add_command(label='About')

mainloop()

          output-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-9.png

 

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

The general syntax is:

w = Message(master, option=value)

master is the parameter used to represent the parent window.

Example-> from tkinter import *

main = Tk()

ourMessage ='This is our Message'

messageVar = Message(main, text = ourMessage)

messageVar.config(bg='lightgreen')

messageVar.pack( )

main.mainloop( )

          output-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-10.png

 

Scrollbar It refers to the slide controller which will be used to implement listed widgets.

The general syntax is:

w = Scrollbar(master, option=value)

master is the parameter used to represent the parent window.

Example-> from tkinter import *

root = Tk()

scrollbar = Scrollbar(root)

scrollbar.pack( side = RIGHT, fill = Y )

mylist = Listbox(root, 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()

          output-> https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-68-13.png