I remember an incident from a couple of years back. It was a corporate setting and I was giving a presentation in one of those ‘Knowledge Sharing‘ sessions to an audience of roughly 50 people who had gathered around to watch my humble presentation about Python and its vast variety of potential applications in field of Process Automation.
The session had started to become a bit boring and I had a tonne of demos which although interesting had started to become a little monotonous. ( A few yawns , here and there. Couple of eye rolls etc)
That’s when I thought of ditching a few of the demo videos I had prepared and do something interesting instead.
I asked the audience, “How many of you people use Facebook everyday?” . Responding to which, the majority (if not all) had lifted their arms ( rather lazily though!) .
At this point, you might think what a doofus I am, to ask the obvious, but then corporate setting, central air conditioning , cozy chairs and a guy giving you a boring tech presentation…you catch my drift.Right? I had to do something to catch my audience’s attention and hence the question.
” How many of you wish people on their birthdays on Facebook regularly? ” was my next question. To which only a few people had raised their hands.
“Do you wish there was something , a system , an automation that can automatically post wishes on their timeline , so you don’t miss out on wishing them (and remain in their good books forever) ?”
I got a few sneers here and there and ‘Oh-My-God-What-a-dubious-Bloke‘ looks from few people but the deed was done – The mission was accomplished – I was In – I had their attention – I had the controls.
From their on, I went ahead with how to create a simple bot using Python and seleniumwebdriver to automate basic tasks in Facebook like makingbirthdayposts, liking posts and pictures , making status updates,etc.
Here is the demo showing the working of the bot that I created!
I have made a very very basic GUI for the primary purpose of fetching username and password. I could have done the same without making a GUI by using getpass module but getpass module displays or echoes back the password in some exceptional cases.
Therefore , I decided to go ahead with creating a fool proof GUI form which masks sensitive data (password field) with asterisks.
Also a tkinter GUI form enables my idea of event driven programming that I have for running this app.
Areas of improvement for this App could be:-
Functionality to view stories
Post status updates at time intervals.
Scrape special word containing posts and saving them or emailing them.
Fetch likes information.
If you like this tutorial you can subscribe to my blog for more of such cool programming projects using Python. If you have any queries you can email me at: piushgoutam@gmail.com
Have you ever wondered how Desktop applications are designed and built?
How a user interface interacts with back-end code to create a fully running app?
Forget software. How can a small thing, join up with something else to finally become a complete object that unitedly acts to a common purpose?
I can’t speak for the majority of you out there but if you are one of those people who has created something out of nothing, you can relate to me when I say that the feeling, the rush of it, is nothing short of magic!
Here we are looking at one such simple project built completely out of the scratch which any newbie programmer, student, teen or any hobbyist in general can give a try. This is a basic Newsreader app which uses python requests module (to mine news articles),BeautifulSoup (to parse HTTP Responses) and Tkinter module (to create the layout and UI of the app).
Pre- Requisites:-
1) Basic idea of what parsing is, and how an HTML document is structured.
2) Basic Python Syntax. List and dictionary comprehensions and what a JSON file actually is.
( However, If you find yourself short of having these prerequisites,I would advise you not to panic and please be assured this tutorial might just help you learn something about all the above. Happy Reading!)
This script is going to make the use of two Python modules, Tkinter and BeautifulSoup. Tkinter is a module for designing user interfaces to your back-end code in order to make them more user friendly and it comes with basic python packaging. (inbuilt module) where as Beautifulsoup is a module written in Python for parsing HTML , XML , JSON type of data which is basically what the majority of websites use to present data.
you can pip install Beautifulsoup by opening up a cmd window / terminal and typing in,
pip install bs4
provided you have the path to pythonw.exe mentioned in your PATH Environmental variable(for Windows).
Let us begin by learning how to design a good looking interface as the one shown above. If you have had a prior experience in Python Tkinter programming you probably know and possibly think that you might not be able to make some pretty high end looking Interface using Tkinter. – In my career, the majority of people I meet prefer to work on Kivy – Agreed, Kivy is better than Tkinter for building more mobile and cellphone based apps (basically touch-based apps).
But, for building localized Desktop apps like these, I would still suggest to try your hand out with Tkinter before jumping on to something bigger.
Designing the main window :
We are going to start with creating an outer window which we shall name as ‘root’ and set it’s geometry, background colors and visibility. For this, we are going to start by importing required packages and declaring a class a shown below
So, we import tkinter for creating GUI, PIL (pillow) for interacting with images of different format (do a pip install) , time to fetch local time and introducing delays where necessary.
We start by declaring a class MainApp and declaring an __init__ method. This __init__ method is basically what is called first when you call the MainApp class after declaring an object.
import tkinter as tk
from bs4 import *
from tkinter import *
from PIL import Image, ImageTk
import time
class MainApp:
def __init__(self):
root = Tk()
root.title("NewsReader App")
root.geometry('1000x1000')
root.resizable(False,False)
root.configure(background="white")
root.wait_visibility(root)
root.wm_attributes('-alpha',0.85)
I am going to take an Object oriented approach by constructing the rest of the app GUI in the __init__ method as it gives a better case of code re-usability, manipulating an element in the UI from anywhere in the program and independence from the need to declare an underlying function before accessing it.
So, let us understand what is happening in the code here.
root = Tk()
will be generating an empty window as shown below
Now we need to set the dimensions and give this window a proper title. So I am going to give it a title as “NewsReader App” and I will set it’s dimensions to 1000×1000 pixels with the following commands.
You can see , the window’s dimensions has increased. And the title has changed to ‘NewsReader App’.
The command “root.resizable..” sets the window dimensions as fixed. This is important if you want to render your app properly. root.resizable(False,False) means you are setting the –resizable property as False for x-axis as well as y-axis simulatenously. Hence the 2 falses.
Now that, a basic window has been made, we are going to stylize this window by implementing a few features which gove our app a very modern look. We are going to tinker with the opaqueness of the app and make it look a little transparent so as the app doesn’t cover up a large portion of our screen and renders our visibility of other windows useless.
You can see the window has become somewhat transparent allowing us visibility of windows lying underneath it.
root.wm_attributes() has a property -alpha whose value ranges from 0 to 1. Where 0 is completely transparent and 1 is completely opaque. So we adjust this value as per our requirements.
Before we proceed further, let us take a look at how our UI is going to be structured.
This is an outline of the UI that we are going to create. Generally it is a good practice to design an outline beforehand before we begin implementation
Now that we have our basic design ready, we will directly jump to building it right away. We shall start with putting a frame first on the root window. This is done by
I have used pack() instead of grid() or place() because I want my UI to look very compact and minimalistic. Grid is used when you probably want to place your elements in a tabular format (This was quite the norm some 10-15 years ago, for some reason! ) . Place is used when you want to place the elements in a coordinate fashion. place(x = 20, y = 20) will put the element in coordinates 20,20 from left and top margins respectively.
Also note that I have used a shade of gray known as gray19 for the color of my frame background. There exists a wide list of colors to choose from in Tkinter and you can choose whichever color you may like. However, my advice would be to stick to grays, silvers, olives or light blues or lighter colors in general if you want you app to keep looking professional.
greeting_label = tk.Label(self.frame1,
text='Welcome to your Personal News Reader',
font = ('URW Bookman L',18),
fg = 'white', bg='skyblue3').pack(expand='no', fill=tk.X)
So far so good!
Let us now put in a label where we display real time. This will be helpful as it can help create a track of amount of time we have spent in the reader app. So here we go with the code
You can observe 2 things here clearly. I have used the time module to directly fetch the local time and I have passed it as label text itself. This is necessary as we want to have a display that is real time and not static.
Secondly, you see me calling a method update_time() .So we need to define update_time method as below
Basically, this function is designed to update the watch label continuously with a set time interval of 200 ms. 200 ms why? You may ask. Because, any value above 200 ms will make the app look glitchy and blurry. This function does so by calling itself again and again after every update.
This being done, lets have a look.
Let us add a catchy tagline now to make the app look very promising and marketable!
self.fetch_label = tk.Label(self.frame1,
text = "Read Top News, Headlines, Sports,Business, Entertainment News\n..All in one place!",
font = ('Ubuntu condensed',12),
fg = 'orange',
bg = 'gray19')
self.fetch_label.pack(expand = 'no', fill = tk.X , pady = 10)
Great, now let’s jump on to creating the second frame of our root and put in a label with text ‘Categories’ into it.
My idea is to have 7 different categories corresponding to the topics I like to read about. You are free to have as many topics as you want, and you will have to edit your code accordingly.
These categories would be:- India, Sports, Science,Entertainment, Business, World and Miscellaneous news. We are going to be needing some really funky looking icons if we want our app to look good. In my case, I have GoogleImagesearched for these terms and downloaded these .png files (or vector files) and resized them to 200X200 (for visual purpose). (You are free to have custom adjustments)
These images are then referenced into photo- variables as shown above using PhotoImage method.
We then, used Buttons as buttons enables event driven programming and images can be set in place of plain boring text. This is what we do in the code above.
Take a not of the fact, that I have used statements like ‘c2.image = photo2’ . This is done to reinforce the image to the button and bypass the problem of Tkinter allocating garbage values as image bytes. (which you may face if these statements are absent).
You will also see that I have used grid() in place of pack() as I intend to present my icons in a proper grid format!
Note:- You must not use grid() and pack() in a same widget level. In this case, I have used grid() to pack these icons to the parent_label which is further packed to frame2 using pack(). Take a not of the fact that these both are not used in the same widget level.
some attributes like –borderwidth and highlightthickness are used here to be set to 0 so as to give the app a good look. You will really not want your App to be marred with dirty looking borders!
Finally we use root.mainloop() to loop the entire window to keep it running in python memory.
Now that our User Interface is ready. We will move forward to creating the backend running code for our application. We will discuss this in the next part of this blog post.
I hope you can now believe, Good Looking UIs can definitely be designed in Tkinter itself!
If you like this tutorial you can subscribe to my blog for more of such cool programming projects using Python. If you have any queries you can email me at: piushgoutam@gmail.com