tags:

views:

31

answers:

2

I'm not being able to make this line work with Tk

import os
while(1):
    ping = os.popen('ping www.google.com -n 1')
    result = ping.readlines()
    msLine = result[-1].strip()
    print msLine.split(' = ')[-1]

I'm trying to create a label and text = msLine.split... but everything freezes

A: 
Charles Merriam
steel freezes =/
Shady
A: 

Your example code shows no GUI code. It is impossible to guess why your GUI freezes without seeing the code. Though, your code is pretty buggy so even if there were GUI code in your post it likely wouldn't help.

Is it possible that you're forgetting to call the mainloop() method on your root widget? That would explain the freeze. And if you are calling mainloop(), there's no reason to do while(1) since the main event loop itself is an infinite loop. Why are you calling ping in a loop?

One specific problem you have is that you are calling ping wrong. For one, the option "-n 1" needs to come before the hostname argument (ie: 'ping -n 1 www.google.com' instead of 'ping www.google.com -n 1'). Also, -n is the wrong thing to do. I think you want "-c 1"

Here's a working example of how you can ping periodically and update a label:

import os
from Tkinter import *
class App:
    def __init__(self):
        self.root = Tk()
        self.create_ui()
        self.url = "www.google.com"
        self.do_ping = False
        self.root.mainloop()

    def create_ui(self):
        self.label = Label(self.root, width=32, text="Ping!")
        self.button = Button(text="Start", width=5, command=self.toggle)
        self.button.pack(side="top")
        self.label.pack(side="top", fill="both", expand=True)

    def toggle(self):
        if self.do_ping:
            self.do_ping = False
            self.button.configure(text="Start")
        else:
            self.do_ping = True
            self.button.configure(text="Stop")
            self.ping()

    def ping(self):
        if not self.do_ping:
            return
        ping = os.popen('ping -c 1 %s' % self.url)
        result = ping.readlines()
        msLine = result[-1].strip()
        data = msLine.split(' = ')[-1] 
        self.label.configure(text=data)
        # re-schedule to run in another half-second
        if self.do_ping:
            self.root.after(500, self.ping)

app=App()
Bryan Oakley