2016-05-14 144 views
-1

我试图循环这个,但每次都失败。 这是我试图循环的def create_widgets。所以我有一个图形用户界面,只要有东西脱机,就会显示一个红色的按钮/框。如何循环此代码?

这是我尝试使用的代码。

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() 
+0

你想整函数循环的第一次执行? –

+0

在不相关的说明中,您通常不希望导入模块,而只是程序的开始。 –

+0

我的回答有帮助吗?如果没有,请告诉我,以便我可以编辑它。 –

回答

2

您可以将它放到小号after方法Tk“使用Tk的活动中循环”。

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" 

然后,该线去任何地方app = Application(root)root.mainloop()之间:

root.after(0, app.if_offline) 

after附加一个过程到Tk事件循环。第一个参数是过程应该以毫秒为单位重复的次数,第二个参数是要执行的函数对象。由于我们指定的时间是0,它会不断检查并不断更新按钮的背景颜色。如果这会搅动你的CPU,或者你不想那么多,你可以将重复时间改变成更大的。

传入的函数对象应该只是:函数对象。它具有与构造函数Button中的命令参数相同的规则。 如果您需要在参数传递给函数,使用lambda像这样:

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

这工作,因为lambda函数返回一个函数对象,被执行时将运行function(argument)

Source

+0

嗨 我是新来编程,所以我不明白为什么我写这个错误。 NameError:名称'root'未定义 root.after(0,if_offline) root.mainloop() – user6335058

+0

尝试向类中的所有内容添加一个缩进。 –

+0

我的错误。它需要'app.if_offline'而不是'if_offline'。我编辑了包含该答案的答案。 –