×

Text detection using Tkinter in Python

Tkinter:

The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is this one. On top of Tk, this Python framework serves as a thin object-oriented layer that provides access to the Tk toolkit. The Tk toolkit is a cross-platform set of "graphical control elements," also called widgets, used to build application interfaces. This framework gives Python users a quick and easy way to build GUI elements with the Tk toolkit's widgets. In a Python application, Tk widgets can create buttons, menus, data fields, etc.

Once created, these graphic elements can be connected to or work with other widgets, features, functionality, processes, or data.

Tkinter bridges the gap between Python's execution model and Tcl's, built around cooperative multitasking. Like Python, Tcl is an interpreted dynamic programming language. Although it is an overall programming language that can be used independently, it is most frequently used in C programs as a scripting motor or as an interaction with the Tk toolbox. The Tcl library has a C interface that enables users to add custom Tcl or C commands, run Tcl commands and scripts, and manage one or more Tcl interpreter instances. Each interpreter has a queue for events that can be used to send and process events.

Syntax:

from tkinter import *
from tkinter import ttk

Advantages of Tkinter:

This promotes flexibility in handling GUI incidents, which makes the code base run more smoothly. Qt is more than just a framework; it uses a variety of native platform APIs for networking, database development, and other uses. Through a unique API, it gives them direct access.

Disadvantages of Tkinter:

Tkinter doesn't have any advanced widgets. There isn't a tool like Qt Designer for Tkinter in it. Its user interface is unreliable. Tkinter can be challenging to debug at times. It's not entirely in Python.

  • The lexicon- and rule-based sentiment analysis tool VADER (Valence Aware Dictionary and sEntiment Reasoner) is customized precisely to sentiments expressed on social media. VADER makes use of a variety of. A sentiment lexicon is a collection of linguistic elements (such as words) that are often classified as either negative or positive depending on their semantic orientation. VADER informs us of the positive and negative scores and only informs us of the positive and negative scores but also the sentimentality of each score.

CODE:

import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
import tkinter.messagebox
from nltk.sentiment.vader import SentimentIntensityAnalyzer
  
     
class analysis_text():
     
    
    def center(self, toplevel):
         
        toplevel.update_idletasks()
        w = toplevel.winfo_screenwidth()
        h = toplevel.winfo_screenheight()
        size = tuple(int(_) for _ in
                     toplevel.geometry().split('+')[0].split('x'))
         
        x = w/2 - size[0]/2
        y = h/2 - size[1]/2
        toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))
  
    def callback(self):
        if tkinter.messagebox.askokcancel("Quit",
                                          "Do you want to leave?"):
            self.main.destroy()
  
    def setResult(self, type, res):
         
        if (type == "neg"):
            self.negativeLabel.configure(text =
                                         "you typed negative comment : "
                                         + str(res) + " % \n")
        elif (type == "neu"):
            self.neutralLabel.configure( text =
                                        "you typed  comment : "
                                        + str(res) + " % \n")
        elif (type == "pos"):
            self.positiveLabel.configure(text
                                        = "you typed positive comment: "
                                         + str(res) + " % \n")
         
  
    def runAnalysis(self):
         
        sentences = []
        sentences.append(self.line.get())
        sid = SentimentIntensityAnalyzer()
         
        for sentence in sentences:
             
            ss = sid.polarity_scores(sentence)
             
            if ss['compound'] >= 0.05 :
                self.normalLabel.configure(text =
                                           " you typed positive statement: ")
    
            elif ss['compound'] <= - 0.05 :
                self.normalLabel.configure(text =
                                           " you typed negative statement")
    
            else :
             self.normalLabel.configure(text =
                                        " you normal typed  statement: ")
            for k in sorted(ss):
                self.setResult(k, ss[k])
        print()
         
  
    def editedText(self, event):
        self.typedText.configure(text = self.line.get() + event.char)
         
  
    def runByEnter(self, event):
        self.runAnalysis()
  
 
    def __init__(self):


        self.main = Tk()
        self.main.title("Text Detector system")
        self.main.geometry("600x600")
        self.main.resizable(width=FALSE, height=FALSE)
        self.main.protocol("WM_DELETE_WINDOW", self.callback)
        self.main.focus()
        self.center(self.main)
  
        self.label1 = Label(text = "type a text here :")
        self.label1.pack()
  
        self.line = Entry(self.main, width=70)
        self.line.pack()
  
        self.textLabel = Label(text = "\n",
                               font=("Helvetica", 15))
        self.textLabel.pack()
        self.typedText = Label(text = "",
                               fg = "blue",
                               font=("Helvetica", 20))
        self.typedText.pack()
  
        self.line.bind("<Key>",self.editedText)
        self.line.bind("<Return>",self.runByEnter)
  
  
        self.result = Label(text = "\n",
                            font=("Helvetica", 15))
        self.result.pack()
        self.negativeLabel = Label(text = "",
                                   fg = "red",
                                   font=("Helvetica", 20))
        self.negativeLabel.pack()
        self.neutralLabel  = Label(text = "",
                                   font=("Helvetica", 20))
        self.neutralLabel.pack()
        self.positiveLabel = Label(text = "",
                                   fg = "green",
                                   font=("Helvetica", 20))
        self.positiveLabel.pack()
        self.normalLabel =Label (text ="",
                                 fg ="red",
                                 font=("Helvetica", 20))
        self.normalLabel.pack()
myanalysis = analysis_text()
mainloop()

CODE EXPLANATION:

Importing all the required modules which are Time, Pandas, numpy, matplotlib, tkinter Adding a main function in the program to update, winfo_screenwidhth, winfo_screenheight, dimensions including geometry. Next calculate comments in vader analysis. Create a main window using main() method that are Title, geometry, resizable, protocol, focus. Adding addition item on window that is hidden entry button.

OUTPUT:

Text detection using Tkinter in Python

Related Topics

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.