如何让Tkinter方块根据Ping结果自动切换背景颜色
Auto-Update Square Colors Based on Ping Results
Got it, let's adjust your code so the squares automatically reflect the ping status of each IP as soon as the program launches—no manual clicks needed. Here's the modified version with clear improvements:
Modified Full Code
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: str, timeout: int = 100) -> bool: # Use OS-appropriate ping flag num_flag = '-n' if platform.system().lower() == 'windows' else '-c' completed_ping = subprocess.run( ['ping', num_flag, '1', '-w', str(timeout), ipAddr], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=False ) # Verify both return code and TTL to confirm valid ping response success = completed_ping.returncode == 0 and b'TTL=' in completed_ping.stdout status = "Network Active " if success else "Network Error " print(f"{status}{ipAddr}") return success ### Function to ping all IPs and return results def multiping(ip_list: dict) -> dict: ping_results = {} for name, ip in ip_list.items(): ping_results[name] = ping(ip) return ping_results class OneSquare(): def __init__(self, can, start_x, start_y, size): self.can = can # Start with red (default: ping failed) self.id = self.can.create_rectangle( (start_x, start_y, start_x+size, start_y+size), fill="red" ) def update_color(self, is_active: bool): # Set green if ping succeeded, red otherwise color = "green" if is_active else "red" self.can.itemconfigure(self.id, fill=color) if __name__ == "__main__": root = Tk() root.title("Network Status Monitor") canvas = Canvas(root) canvas.grid(column=1, row=1, sticky=(N, S, E, W)) # Map each IP entry to its corresponding square square_map = { 'test': OneSquare(canvas, 1, 1, 30), 'test 2': OneSquare(canvas, 1, 50, 30), 'test 3': OneSquare(canvas, 1, 100, 30) } # Exit button Button(root, text="Exit", bg="orange", command=root.quit).grid(row=2, column=1) # Run ping checks and update square colors automatically ping_results = multiping(iptoscan) for ip_name, is_active in ping_results.items(): square_map[ip_name].update_color(is_active) root.mainloop()
Key Changes Breakdown
Fixed the
pingfunction:- Ditched the global variable (no need for it—we just return the success status directly)
- Renamed variables to follow Python's naming conventions for readability
- Kept the TTL check to avoid false positives (some systems might return 0 even for invalid pings)
Rewrote
multiping:- Now returns a dictionary of results for every IP, instead of bailing after the first success
- Takes the IP list as a parameter, making it more flexible
Updated
OneSquareclass:- Removed the click event binding since we don't need manual color toggling anymore
- Added an
update_colormethod that accepts a boolean to set the correct color based on ping status - Initialized squares as red (the default state for failed pings)
Mapped IPs to Squares:
- Created a
square_mapto link each IP entry name to its square—this ensures we update the right box for each ping result
- Created a
Auto-Run Ping on Startup:
- Right after setting up the UI, we run the ping checks and update all squares automatically before starting the main loop
内容的提问来源于stack exchange,提问作者Lucas Abreu
相关产品推荐
相关产品推荐

