Skip to main content
1 of 3
Chris
  • 241
  • 1
  • 2

Python program that checks connection based on URLLIB response

import urllib
import urllib.request as url
from tkinter import *

master = Tk()
master.geometry("280x36")
master.resizable(False, False)
master.config(bg="#4b4b4b")
master.overrideredirect(True)

master.wm_geometry("-0-40")
master.wm_attributes("-topmost", 1)

connectStatus = Label(bg="#e67e22", fg="#fff", width=29, height=1, text="Pending", font="Bahnscrift 10")
connectStatus.place(x=10,y=8)

closeButton = Button(width=2, bg="#706f6f", fg="#fff", borderwidth=0, text="x", command=master.destroy)
closeButton.place(x=253, y=8)

def displayCheck():
    if callbackAttempt == 1:
        connectStatus.config(bg="#38f789")
        master.after(10, runRefresh)
        
    else:
        connectStatus.config(bg="#ff6656")
        master.after(10, runRefresh)
        
def runRefresh():
    attemptConnect()
    master.after(2000, displayCheck)

def attemptConnect():
    global callbackAttempt
    
    try:
        callbackAttempt = 1
        callback = url.urlopen("https://stackoverflow.com", timeout=1)
        connectStatus.config(text="Connection Established", font="Bahnscrift 10", bg="#2ecc71")
        callback.close()

    except urllib.error.URLError:
        connectStatus.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
        callbackAttempt = 0
    
master.after(5, runRefresh)
master.mainloop()

This is my program, the main function trys to create a urllib connection, and if it fails/succeeds the label changes accordingly. However, I'm looking for ways to improve this code. If anyone has any ideas- I'd appreciate it.

Some elements I'm already aware of -

  • The use of place really isn't ideal, I'm aware
  • Importing Urllib twice, but if I didn't do it like this the except: wasnt working correctly
  • Use of global
Chris
  • 241
  • 1
  • 2