Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 code I tried to use.

from tkinter import *

class Application(Frame):
""" GUI """

def __init__(self, master):
    """ Initialize the Frame"""
    Frame.__init__(self,master)
    self.grid()
    self.create_widgets()

def create_widgets(self):
    """Create button. """
    import os
    #Router
    self.button1 = Button(self)
    self.button1["text"] = "Router"
    self.button1["fg"] = "white"
    self.button1.grid(padx=0,pady=5)
    #Ping
    hostname = "10.18.18.1"
    response = os.system("ping -n 1 " + hostname)
    #response
    if response == 0:
        self.button1["bg"] = "green"
    else:
        self.button1["bg"] = "red"

root = Tk()
root.title("monitor")
root.geometry("500x500")

app = Application(root)

root.mainloop()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

def if_offline(self):
    #Ping
    hostname = "10.18.18.1"
    response = os.system("ping -n 1 " + hostname)
    #response
    if 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...