'Using Ping constantly to verify connection and display feedback on python tkinter

I am trying to make a small app with python tkinter. in which i will need a ping command to constantly check for connection to a certain device example '192.168.1.21' and tells me if the device is connected or not real time. Nota: i am using ping3 this is my program:

root = Tk()
root.geometry("400x400")
label_1 = Label(root, text = "Not connected")
label_1.pack()




def testing(label):
    if ping('192.168.1.21', timeout=0.5) != None: #To test the connection 1 time
        label.config(text = "Connected")
    else:
        label.config(text = "Not Connected")

    label.after(500, lambda : testing(label_1))

def popup(): #A popup that does the same thing
    top = Toplevel(root)
    top.geometry("150x150")
    label_2 = Label(top, text = "Not connected")
    label_2.pack()
    label_2.after(500, lambda : testing(label_2))
    top.mainloop()

btn = Button(root, text = "Popup", command=popup)
btn.pack()

testing(label_1)

root.mainloop()

How can i make it not freeze and keep testing while letting the rest of the program run smoothly. Thank you and sorry if I made mistakes in the code, i am still new to python in generale.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source