Skip to content Skip to sidebar Skip to footer

How To Loop This Code?

I have trying to loop this but fail everytime. It´s the def create_widgets I try to loop. So I got a GUI that show a red button/box as soon something goes offline. This is the cod

Solution 1:

You can attach it onto Tk's event loop using Tk's after method.

defif_offline(self):
    #Ping
    hostname = "10.18.18.1"
    response = os.system("ping -n 1 " + hostname)
    #responseif response == 0:
        self.button1["bg"] = "green"else:
        self.button1["bg"] = "red"

Then, this line goes anywhere between app = Application(root) and root.mainloop():

root.after(0, app.if_offline)

after attaches a process onto the Tk event loop. The first argument is how often the process should be repeated in milliseconds, and the second is the function object to be executed. Since the time we have specified is 0, it will constantly check and constantly update the button's background color. If that churns your CPU, or you don't want to be pinging that much, you can change the repeat time to something larger.

The function object passed in should be just that: a function object. It has the same rules as the command argument in a Button constructor. If you need to pass in arguments to the function, use a lambda like so:

root.after(0, lambda: function(argument))

This works because the lambda function returns a function object, which when executed will run function(argument).

Source

Post a Comment for "How To Loop This Code?"