[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


On Tue, Mar 19, 2019 at 3:33 AM Informatico de Neurodesarrollo
<infneurodcr.mtz at infomed.sld.cu> wrote:
> Hello friends:
> I am a beginner on programming in python.

Cool! Then I would recommend making your program as simple as you possibly can.

> I want make a simple program that test continuously (every 5 seg) the
> connection  to internet and change the background color when are not
> available. I try this , but not work properly:
>   #!/usr/bin/env python3
> # -*- coding: utf-8 -*-
> #
> from tkinter import *
> import socket, time
> def DetectarConexion():
>      testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>      try:
>          testConn.connect(('', 80))
>          testConn.close()
>          return True
>      except:
>          testConn.close()
>          return False

This part of the code is completely independent of the Tkinter code.
Split it up into the two parts and develop each one separately.

> root = Tk()
> root.title("Conexi?n")
> root.geometry("80x50")
> while True:
>      if DetectarConexion():
>          # Background:Green
>          root.config(background="#38EB5C")
>      else:
>          # Background:Red
>          root.config(background="#F50743")
>      time.sleep(5)
> root.mainloop()

You have two separate parts to this code, and it's possible that
neither of them is working. I would recommend concentrating first on
the connection status function. Remove everything about Tkinter, and
replace it with a simple print() call:

while True:
    if DetectarConexion():
        print("Connection is happy")
        print("Connection is down!")

Now you can work on making sure your connection tester is working.
What exactly are you testing? What goes wrong when you don't have a

Specific advice:
1) Avoid using the bare "except:" clause. It may be hiding bugs in your code.
2) Make sure you're trying something that actually does work.
Connecting to port 80 isn't going to succeed even if your
connection is live.

Start with that, and you should be able to get a lot further with your testing.

Have fun with it! If you run into trouble, post your updated code,
what you're trying, and what's happening.

Chris Angelico