im trying to do a simple program in Python to send a message when my web valor changes (just context), the question is im doing a loop with tkinter to show a window, i have declared a function that is called in my tkinter loop, i have global variables, but when i change an global variable into the loop, at the next round the variable returns to the initial valor, here is my code:
#just variables (i have simplified the code)
aux1 = False
aux2 = False
aux3 = False
def search(url, aux):
try:
host_get = request.get(ip)
if host_get.status_code == 200:
host_cont = host.get.text
host_soup = BeautifulSoup(host_cont, 'lxml')
try:
host_stat = host_soup.find('div', class='UP'.getText())
aux = False
except:
if aux == False:
MessageBox.showWarning("Alert", "Host is DOWN")
aux = True
#The problem is here
#After doing this (aux = True), the program still doing (aux = False) options
elif aux == True:
print("Host still DOWN")
else:
MessageBox.showWarning("Alert", "Host is DOWN")
aux = True
def search_loop:
#i have many websites, but i showed only 1 for the example code
url1 = "website1.com"
global aux1
search(url1, aux1)
#5 seconds to do the next loop
time.sleep(5)
class WindowClass:
def __init__(self):
self.window1 = tk.Tk()
self.button1()
self.window1.mainloop()
def button1(self):
self.startbutton = tk.Button(self.window1, command=self.startloop, text='Start')
self.startbutton.place(x=50, y=50)
def startloop(self):
search_loop()
app1 = WindowClass()
yep, its a infinite loop, the problem i have is on the loop i think, but idk, i have tried many things to do it correctly but i cant, so arrived here, hope someone can help me, sorry for the broken english, idk if i explained correctly.
you can't pass global variables around as parameters. You are passing a copy of the global variable into your search function, which is why the modification is lost.
Try changing you code so that you use the globals directly:
aux1 = False
aux2 = False
aux3 = False
def search():
global aux1, aux2, aux3
aux1 = True
class main():
def __init__(self) -> None:
search()
print(aux1)
print(aux2)
print(aux3)
# result
# True
# False
# False
main()