Search code examples
pythonfor-loopbuttonkivyhost

Changing the background color for buttons for each alive Host in Python


I have 4 buttons, each one dedicated to a host

I would like to ping each host and change the button background color to ( green or red) in case the ping is successful(green) or not(red).

I can make that in 4 different functions, but it will be much better and faster if it's in one function

Here is the function:

def Check(self):

    hosts = ['192.168.178.211', '192.168.178.212', '192.168.178.213', '192.168.178.214']

    for i in hosts:

        response = os.system("ping -n 1 -w 500 " + i + " > nul")

        if response == 0:
            self.button1.background_color = green
            self.button2.background_color = green
            self.button3.background_color = green
            self.button4.background_color = green

        else:
            self.button1.background_color = red
            self.button2.background_color = red
            self.button3.background_color = red
            self.button4.background_color = red

     pass

I think the problem with my code, is that when one host is alive, it will make all the buttons green, which is wrong. Sometimes one host is on and the other is off, and I would like to present the Live state with the background color of the button.


Solution

  • You can create a list for buttons and enumerate in loop and change the background color of the right button. Below is the corrected function:

    def Check(self):
    
        hosts = ['192.168.178.211', '192.168.178.212', '192.168.178.213', '192.168.178.214']
        buttons = [self.button1, self.button2, self.button3, self.button4]
        
        for x, i in enumerate(hosts):
    
            response = os.system("ping -n 1 -w 500 " + i + " > nul")
    
            if response == 0:
                buttons[x].background_color = green
            else:
                buttons[x].background_color = red
    
         pass