Search code examples
python-3.xtkinterqueuepython-multithreadinginternet-connection

Real Time internet connection checker in python With GUI


so basically what i am trying to do is to check if the computer have access to internet till the end of the program....

It is in a GUI which is made with tkinter.....I tried to create new thread and run the function in a while loop(while 1:), but it says

Traceback (most recent call last):

.

.

.

RuntimeError: main thread is not in main loop

this is the program

import threading
import socket
import time

def is_connected():
    try:
        socket.create_connection(("www.google.com", 80))
        print("Online",end="\n")
    except OSError:
        print("offline",end="\n")

tt3 =threading.Event()

while 1:
    t3=threading.Thread(target=is_connected)
    t3.start()
    time.sleep(1)

This is the program with GUI

import threading
import socket
import time
import tkinter
top = tkinter.Tk()
top.title("")
l=tkinter.Label(top,text='')
l.pack()

def is_connected():
    try:
        socket.create_connection(("www.google.com", 80))
        print("Online",end="\n")
        l.config(text="Online")
    except OSError:
        l.config(text="offline")
        print("offline",end="\n")

tt3 =threading.Event()

while 1:
    t3=threading.Thread(target=is_connected)
    t3.start()
    time.sleep(1)

top.configure(background="#006666")
top.update()
top.mainloop()

any suggestion or help is most welcomed!! (someone in reddit suggested me to use queue about which i have no idea )


Solution

  • First the while loop will block the tkinter mainloop from processing events. Second you are repeatedly creating new thread in each loop.

    Better use .after():

    import socket
    import tkinter
    
    top = tkinter.Tk()
    top.title("Network Checker")
    top.configure(background="#006666")
    
    l=tkinter.Label(top,text='Checking ...')
    l.pack()
    
    def is_connected():
        try:
            socket.create_connection(("www.google.com", 80)) # better to set timeout as well
            state = "Online"
        except OSError:
            state = "Offline"
        l.config(text=state)
        print(state)
        top.after(1000, is_connected) # do checking again one second later
    
    is_connected() # start the checking
    top.mainloop()