2015-10-06 62 views
0

我想ping我的網絡中的每秒鐘一個特定的主機名並更改相應按鈕的名稱。 現在我有這樣的:Ping每秒鐘和Tkinter按鈕

import tkinter as tk 
import time 

# variables 
hostname = ("ASUS-PC") 
mot= "inactif" 

class test(tk.Tk): 
    # make buttons on grid 
    def __init__(self): 
     tk.Tk.__init__(self) 

     self.button = list() 
     for i in range(10): 
      i=i+1 
      RN = ('RN '+str(i)) 
      self.button.append(tk.Button(text=RN)) 
      self.button[-1].grid(row=0,column=i) 
    # ping hostname every second 
    def ping(self): 
     import subprocess 
     import os 
     result=subprocess.Popen(["ping", "-n", "1", "-w", "200", hostname],shell=True).wait() 
     if result == 0: 
      print (hostname, "active") 
     else: 
      B = self.button[0] 
      B ['text'] = mot 

     time.sleep(1) 
    while True: 
     ping() 

app = test() 
app.mainloop() 

它不工作,我不知道爲什麼。在開始這是一個「自我」的問題,但現在它似乎是關係到我如何PING每一秒(我把它從那裏What is the best way to repeatedly execute a function every x seconds in Python?)如果有人知道答案......

感謝您的幫助

+0

變量'button'在引用時超出了範圍。相關:http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules – Monkpit

+0

你的意思是讓'self.button'(注意你甚至在'ping'缺少適當的參數')?功能中的局部變量不能從外部訪問,**故意**。 – jonrsharpe

回答

0

你的代碼「不起作用」的原因是你有一個無限循環調用sleep。這可以防止事件循環處理任何事件,包括告訴Tkinter刷新顯示的事件。你的程序實際上在工作,你只是看不到任何結果。

的解決方案是使用after打電話給你的函數一次第二。在這些電話之間,tkinter將有時間更新顯示屏,而無需做任何額外的工作。

所有你需要做的是去除調用睡眠,並添加調用after。一旦你這樣做,刪除你的while循環,並調用此功能一次。隨後的Tkinter將調用這個函數每秒一次(大約)

它看起來是這樣的:

def ping(self): 
    <all your other code> 
    self.after(1000, self.ping) 

它看起來有點像遞歸,但事實並非如此。您只需在由Tkinter管理的事件隊列中添加事件即可。當時間到了時,它將該項目從隊列中拉出並執行。

+0

我是Python的初學者。你能給我寫一個你想描述的小例子嗎?這樣我就不會犯錯,並且更好地理解這個方法。感謝:D –

0

非常感謝大家!現在它的工作原理:

... 
    # ping hostname every second 
    def ping(self): 
     import subprocess 
     import os 
     result=subprocess.Popen(["ping", "-n", "1", "-w", "200", hostname],shell=True).wait() 
     if result == 0: 
      print (hostname, "active") 
     else: 
      print (hostname, "inactive") 
      B = self.button[0] 
      B ['text'] = mot 

     self.after(1000, self.ping) 

app = test() 
app.ping() 
app.mainloop() 
+0

我看到你是新來的stackoverflow。如果您還沒有閱讀,請閱讀http://stackoverflow.com/help/someone-answers。 –