import platform
import subprocess
from tkinter import *
###IPs to use
iptoscan = {
'test': '8.8.8.8',
'test 2' : '7.7.7.7',
'test 3' : '1.1.1.1'
}
###Ping function
def ping(ipAddr: object, timeout: object = 100) -> object:
if platform.system().lower() == 'windows':
numFlag = '-n'
else:
numFlag = '-c'
global completedPing
completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
stdout=subprocess.PIPE, # Capture standard out
stderr=subprocess.STDOUT) # Capture standard error
if completedPing.returncode == 0: # I need this if command to send the IP address and a True command
pingstatus = "Network Active " # Active ping response
else: # I need this to send the IP plus a False command
pingstatus = "Network Error " # No ping response
print(pingstatus + ipAddr)
return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)
###Function to ping from dictionary
def multiping():
for ips in iptoscan:
ping(iptoscan[ips])
if completedPing.returncode == 0:
return True
else:
print("notworking")
Мой вопрос
Вместо использования «ButtonPress» я хочу изменить поля с результатом пинга, true становится зеленым, false остается красным. Таким образом, в основном, как только код запускается, я хочу, чтобы он пинговал из словаря, и если результаты верны, я хочу, чтобы он менял цвет каждого поля.
class OneSquare():
def __init__(self, can, start_x, start_y, size):
self.can=can
self.id = self.can.create_rectangle((start_x, start_y,
start_x+size, start_y+size), fill="red")
self.can.tag_bind(self.id, "<ButtonPress-1>", self.set_color)
self.color_change=True
def set_color(self, event=None):
self.color_change = not self.color_change
color="red"
if not self.color_change:
color="green"
self.can.itemconfigure(self.id, fill=color)
root = Tk()
canvas = Canvas(root)
canvas.grid(column=1, row=1, sticky=(N, S, E, W))
#Boxes to display the network status
IP1=OneSquare(canvas, 1, 1, 30)
IP2=OneSquare(canvas, 1, 50, 30)
IP3=OneSquare(canvas, 1, 100, 30)
#Exit button
Button(root, text="Exit", bg="orange",
command=root.quit).grid(row=2)
multiping()
root.mainloop()