Home > Net >  Python Tkinter window not opening
Python Tkinter window not opening

Time:10-14

I made a program that is a bot in python that responds to your commands you say. It uses google speech recognition. I wanted to make a gui with tkinter for it, but the tkinter window is not opening when I run the program. the tkinter program should display your own message and the response of the bot in the window. This is my code

from cgitb import text
from multiprocessing.connection import answer_challenge
from turtle import goto
from typing import Text
from urllib import response
import speech_recognition as sr 
from GoogleNews import GoogleNews
import pyttsx3
import pyjokes
import datetime
from datetime import datetime
import random
import os
import wikipedia
from google_trans_new import google_translator
import webbrowser
import pywhatkit
import subprocess
from tkinter import *
from multiprocessing import Process, Queue



googlenews = GoogleNews()
engine=pyttsx3.init()
voices=engine.getProperty('voices')
engine.setProperty('voice',voices[2].id)
recognizer=sr.Recognizer()
q = Queue()
root = Tk()
root.title("Gideon")

BG_GRAY = "#ABB2B9"
BG_COLOR = "#17202A"
TEXT_COLOR = "#EAECEE"

FONT = "Helvetica 14"
FONT_BOLD = "Helvetica 13 bold"





def resources():
    print("heating up the program")
    googlenews = GoogleNews()
    engine=pyttsx3.init()
    voices=engine.getProperty('voices')
    engine.setProperty('voice',voices[2].id)
    recognizer=sr.Recognizer()
    startup()

def startup():
    name = os.getlogin()
    with sr.Microphone() as source:
            print("Clearing background noises")
            recognizer.adjust_for_ambient_noise(source,duration=5)
    sentences = "Hello i am gideon", f"How can i be of service {name}", f"hello {name}", f"We did not speak for a while {name}"
    opening = random.choice(sentences)
    engine.say(opening)
    engine.runAndWait()
    print("started up")
    listen()
    
    

def listen():
    name = os.getlogin()
    a = "b"
    print("listening")
    

    with sr.Microphone() as source:
            try:
                recordedaudio=recognizer.listen(source, timeout= 99999)
                print("recorded audio")
            except:
                pass 
            
            
    try:
            
            text=recognizer.recognize_google(recordedaudio,language='en_US')
            text=text.lower()
            if "gideon" in text:
                text = text.replace("gideon", "")
                print('Your message:',format(text))
                
            else:
                print("did not match")
                listen()
            

    
            
            if "joke" in text:
                joke = pyjokes.get_joke(language="en", category="neutral")
                print(joke)
                botResponse = joke
                engine.say(joke)
                engine.runAndWait()
                
            if "how are you" in text:
                snt = f"Good as long as my script is up to date and running", "Im doing fine", "as long as you are doing great im doing great"
                snt = random.choice(snt)
                botResponse = snt
                engine.say(snt)
                engine.runAndWait()
                
            if "wikipedia" in text:
                search=wikipedia.summary(text)
                engine.say(search)
                engine.runAndWait()
                botResponse = search
                
        
            if "browser" in text:
                a='Opening your internetbrowser.'
                engine.say(a)
                botResponse = a
                engine.runAndWait()
                webbrowser.open(url="https://duckduckgo.com")
            if 'time' in text:
                time = datetime.now().strftime('%I:%M %p')
                print(time)
                botResponse = time
                engine.say(time)
                engine.runAndWait()
            if 'play' in text:
                a='opening youtube..'
                botResponse = a
                engine.say(a)
                engine.runAndWait()
                pywhatkit.playonyt(text)
            if 'news' in text:
                print('Getting news ')
                googlenews.get_news('Today news')
                googlenews.result()
                a=googlenews.gettext()
                botResponse = a
                engine.say(botResponse)
                engine.runAndWait()
            
            send = "You -> "   text.get()
            txt.insert(END, "\n"   send)
            txt.insert(END, "\n"   f"Bot -> {botResponse}")

           
            listen() 
    except Exception as ex:
            print(ex)
            listen()


lable1 = Label(root, bg=BG_COLOR, fg=TEXT_COLOR, text="Welcome", font=FONT_BOLD, pady=10, width=20, height=1).grid(
    row=0)

txt = Text(root, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, width=60)
txt.grid(row=1, column=0, columnspan=2)

scrollbar = Scrollbar(txt)
scrollbar.place(relheight=1, relx=0.974)





resources()

root.mainloop()
        

Does anyone know the solution to this problem please let me know!

CodePudding user response:

Looking at your program from a tkinter-centric point of view, it doesn't have a chance to bring up the interface until/unless everything else in the program works. It might be better to bring up the interface and then fire off the body of the program. This could be a button, but I'll use a timer below and simulate the remainder of the program running with a sleep():

from tkinter import *

BG_COLOR = "#17202A"
TEXT_COLOR = "#EAECEE"

FONT = "Helvetica 14"
FONT_BOLD = "Helvetica 13 bold"

def resources():
    # simulate resources()
    from time import sleep
    sleep(10)

    txt.insert(END, " ready!\n")

root = Tk()
root.title("Gideon")

Label(root, bg=BG_COLOR, fg=TEXT_COLOR, text="Welcome", font=FONT_BOLD, pady=10, width=20, height=1).grid(row=0)

txt = Text(root, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, width=60)
txt.grid(row=1, column=0, columnspan=2)

scrollbar = Scrollbar(root, command=txt.yview)
scrollbar.grid(row=1, column=2, sticky="ns")

txt.configure(yscrollcommand=scrollbar.set)

root.after(1000, resources)

txt.insert(END, "Starting up ...")

root.mainloop()

I also reworked your scroll bar as I'm not convinced your code was working and I was uncertain about the mixing and matching of grid and place. What you did may be fine, but I added a different approach that I was able to confirm is working.

  • Related