v.set
is a method, you are not supposed to write over it as -
v.set = "Internet is online"
You are supposed to call it and pass the string you want to write as argument -
v.set("Internet is online")
And
v.set("Internet is offline! Downtime: " + str(time.time() - start_time))
As noted in the comments, you can also directly set the text value for the label , and then use label.config()
to change the text. Example -
import os, time, tkinter, urllib
from tkinter import *
from urllib.request import *
from urllib.error import *
class App:
def __init__(self, master):
start_time = time.time()
frame = Frame(master)
frame.pack()
if self.internet_on() == 1:
self.label = Label(frame, text="Internet is online")
self.label.pack()
start_time = time.time()
else:
self.label = Label(frame, text="Internet is offline! Downtime: " + str(time.time() - start_time))
self.label.pack()
def internet_on(self):
try:
response=urllib.request.urlopen('http://www.google.com.br',timeout=1)
return True
except urllib.error.URLError as err: pass
return False
top = tkinter.Tk()
app = App(top)
top.mainloop()
The best way to solve your requirement -
In 'internet_on', periodically checking the internet status (change the text in the label). I already tried to use while with no sucess.
Would be to use .after()
method of Tk()
specifying a time in milliseconds (maye something like 5000 milliseconds or so , you can decide this) and specifying the iternet_on method as second argument and then using the internet_on
method update the label. Example -
import os, time, tkinter, urllib
from tkinter import *
from urllib.request import *
from urllib.error import *
class App:
def __init__(self, master):
start_time = time.time()
self.master = master
self.frame = Frame(master)
self.frame.pack()
self.label = Label(self.frame, text="")
self.label.pack()
self.start_time = time.time()
def internet_on(self):
try:
response=urllib.request.urlopen('http://www.google.com.br',timeout=1)
self.label.config(text="Internet is online")
except urllib.error.URLError as err:
self.label.config(text="Internet is offline! Downtime: " + str(time.time() - self.start_time))
self.master.after(5000,self.internet_on)
top = tkinter.Tk()
app = App(top)
top.after(5000,app.internet_on)
top.mainloop()