HOW TO MAKE A VISUAL INTERFACE ON PYTHON + MAKING A CHATBOT
There have many plugins for python to make a visual interface like Tkinter, QT Designer, PyQt, WxPython and much more. There is no such standard GUI interface for Python, you can choose whatever you like. In this post, I choose Tkinter because it is simple for me. If you want to learn more about Tkinter GUI interface, check in this website.
Make a Visual Interface of Calculator
I show you how to make a simple calculator in Tkinter. First open your software where you write a code in Python, in my case it's Komodo Editor and paste this code:# Python program to create a simple GUI
# calculator using Tkinter
# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expressiom
# in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
equation.set(expression)
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.
# Put that code inside the try block
# which may generate the error
try:
global expression
# eval function evaluate the expression
# and str function convert the result
# into string
total = str(eval(expression))
equation.set(total)
# initialze the expression variable
# by empty string
expression = ""
# if error is generate then handle
# by the except block
except:
equation.set(" error ")
expression = ""
# Function to clear the contents
# of text entry box
def clear():
global expression
expression = ""
equation.set("")
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="white")
# set the title of GUI window
gui.title("Calculator")
# set the configuration of GUI window
gui.geometry("300x260")
# StringVar() is the variable class
# we create an instance of this class
equation = StringVar()
# create the text entry box for
# showing the expression .
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing
# the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=5, ipadx=90, ipady=10)
equation.set('')
# create a Buttons and place at a particular
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='grey',
command=lambda: press(1), height=2, width=8)
button1.grid(row=2, column=0, padx=4, pady=4)
button2 = Button(gui, text=' 2 ', fg='black', bg='grey',
command=lambda: press(2), height=2, width=8)
button2.grid(row=2, column=1, padx=4, pady=4)
button3 = Button(gui, text=' 3 ', fg='black', bg='grey',
command=lambda: press(3), height=2, width=8)
button3.grid(row=2, column=2, padx=4, pady=4)
button4 = Button(gui, text=' 4 ', fg='black', bg='grey',
command=lambda: press(4), height=2, width=8)
button4.grid(row=3, column=0, padx=4, pady=4)
button5 = Button(gui, text=' 5 ', fg='black', bg='grey',
command=lambda: press(5), height=2, width=8)
button5.grid(row=3, column=1, padx=4, pady=4)
button6 = Button(gui, text=' 6 ', fg='black', bg='grey',
command=lambda: press(6), height=2, width=8)
button6.grid(row=3, column=2, padx=4, pady=4)
button7 = Button(gui, text=' 7 ', fg='black', bg='grey',
command=lambda: press(7), height=2, width=8)
button7.grid(row=4, column=0, padx=4, pady=4)
button8 = Button(gui, text=' 8 ', fg='black', bg='grey',
command=lambda: press(8), height=2, width=8)
button8.grid(row=4, column=1, padx=4, pady=4)
button9 = Button(gui, text=' 9 ', fg='black', bg='grey',
command=lambda: press(9), height=2, width=8)
button9.grid(row=4, column=2, padx=4, pady=4)
button0 = Button(gui, text=' 0 ', fg='black', bg='grey',
command=lambda: press(0), height=2, width=8)
button0.grid(row=5, column=0, padx=4, pady=4)
plus = Button(gui, text=' + ', fg='black', bg='grey',
command=lambda: press("+"), height=2, width=8)
plus.grid(row=2, column=3, padx=4, pady=4)
minus = Button(gui, text=' - ', fg='black', bg='grey',
command=lambda: press("-"), height=2, width=8)
minus.grid(row=3, column=3, padx=4, pady=4)
multiply = Button(gui, text=' * ', fg='black', bg='grey',
command=lambda: press("*"), height=2, width=8)
multiply.grid(row=4, column=3, padx=4, pady=4)
divide = Button(gui, text=' / ', fg='black', bg='grey',
command=lambda: press("/"), height=2, width=8)
divide.grid(row=5, column=3, padx=4, pady=4)
equal = Button(gui, text=' = ', fg='black', bg='grey',
command=equalpress, height=2, width=8)
equal.grid(row=5, column=2, padx=4, pady=4)
clear = Button(gui, text='Clear', fg='black', bg='grey',
command=clear, height=2, width=8)
clear.grid(row=5, column='1', padx=4, pady=4)
# start the GUI
gui.mainloop()
If you need to install different modules for Python, just go to this website.
When you already do this go to cmd and in console open Python command, in my case look like this:
Then it will open your visual interface calculator, like this:
Make a Visual Interface of Password Generator
Another simple program that generates passwords in Python.
# Python program to generate random
# password using Tkinter module
import random
import pyperclip
from tkinter import *
from tkinter.ttk import *
# Function for calculation of password
def low():
entry.delete(0, END)
# Get the length of passowrd
length = var1.get()
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !@#$%^&*()"
password = ""
# if strength selected is low
if var.get() == 1:
for i in range(0, length):
password = password + random.choice(lower)
return password
# if strength selected is medium
elif var.get() == 0:
for i in range(0, length):
password = password + random.choice(upper)
return password
# if strength selected is strong
elif var.get() == 3:
for i in range(0, length):
password = password + random.choice(digits)
return password
else:
print("Please choose an option")
# Function for generation of password
def generate():
password1 = low()
entry.insert(10, password1)
# Function for copying password to clipboard
def copy1():
random_password = entry.get()
pyperclip.copy(random_password)
# Main Function
# create GUI window
root = Tk()
var = IntVar()
var1 = IntVar()
# Title of your GUI window
root.title("Random Password Generator")
# create label and entry to show
# password generated
Random_password = Label(root, text="Password")
Random_password.grid(row=0)
entry = Entry(root)
entry.grid(row=0, column=1)
# create label for length of password
c_label = Label(root, text="Length")
c_label.grid(row=1)
# create Buttons Copy which will copy
# password to clipboard and Generate
# which will generate the password
copy_button = Button(root, text="Copy", command=copy1)
copy_button.grid(row=0, column=2)
generate_button = Button(root, text="Generate", command=generate)
generate_button.grid(row=0, column=3)
# Radio Buttons for deciding the
# strength of password
# Default strength is Medium
radio_low = Radiobutton(root, text="Low", variable=var, value=1)
radio_low.grid(row=1, column=2, sticky='E')
radio_middle = Radiobutton(root, text="Medium", variable=var, value=0)
radio_middle.grid(row=1, column=3, sticky='E')
radio_strong = Radiobutton(root, text="Strong", variable=var, value=3)
radio_strong.grid(row=1, column=4, sticky='E')
combo = Combobox(root, textvariable=var1)
# Combo Box for length of your password
combo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32)
combo.current(0)
combo.bind('<<ComboboxSelected>>')
combo.grid(column=1, row=1)
# start the GUI
root.mainloop()
Just paste the code and open it, you will see something like this:
Here you can see random password generator, there has a 3 level of strength (Low, Medium and Strong). You can choose the length of your password, generate and copy it!
Make a ChatBot for Telegram
Let's make a ChatBot in Telegram who will tell you what weather is in a particular city and recommends how would you need to dress up. First, you need to install plugin for Python here.
then get your weather API key, to do this, go to this website, register in there and generate an API key.
When you registered in both sites, then in code editor paste this code: (in the red line enter your generated API key before and in yellow line enter created Telegram bot API key):
then get your weather API key, to do this, go to this website, register in there and generate an API key.
After that, we need to create a Telegram Bot! To do this download and install Telegram on your PC. When it's done, register account and in search find: BotFather (enter: /start) to get started creating a bot.
import pyowm
import telebot
owm = pyowm.OWM('Your API key here', language = "eng")
bot = telebot.TeleBot("Your Telegram bot API key")
@bot.message_handler(content_types=['text'])
def send_echo(message):
observation = owm.weather_at_place(message.text)
w = observation.get_weather()
temp = w.get_temperature('celsius')["temp"]
answer = "Country " + message.text + " right now " + w.get_detailed_status() + "\n"
answer += "Temperature now is: " + str(temp) + " degrees" + "\n\n"
if temp < 10:
answer +="It's very cold right now, dress up as warm as you can!"
elif temp < 20:
answer +="Currently are cold, dress up warm!"
else:
answer +="Outside is hot and you can dress like you want!"
bot.send_message(message.chat.id, answer)
bot.polling(none_stop = True)
Then in cmd run a Python command to activate a bot (TelegramBot.py are the name of the file where are code).
Then go to Telegram, open your created bot and write him a country, you will see something like this:
You can learn this bot to do other things, such as displaying a clock in each particular country or something similar. There are many different ways to teach bots, this is just one of them. In next post, I tell you about another different bot makers, like Dialogflow. Good luck and have fun! :)
Comments
Post a Comment