×

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

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Python pycountry

What is Pycountry? Python programming language: 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...

4 minutes read.

Python Banner

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 Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

FOO in Python

Python Programming Language: 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...

3 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.