[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import ttk
import socket
import psutil
import pyperclip
import subprocess
from tkinter import messagebox
def get_network_info():
"""获取网络接口信息"""
network_info = []
addrs = psutil.net_if_addrs()
net_stats = psutil.net_if_stats()
seen_interfaces = set()
for interface in addrs.keys():
if net_stats[interface].isup and interface not in seen_interfaces:
ipv4_address, mac_address = "Not Available", "Not Available"
ipv6_addresses = []
for addr in addrs[interface]:
if addr.family == socket.AF_INET:
ipv4_address = addr.address
elif addr.family == socket.AF_INET6:
if addr.address.startswith("fe80"):
ipv6_addresses.append(f"{addr.address} (内网可用)")
else:
ipv6_addresses.append(addr.address)
elif addr.family == psutil.AF_LINK:
mac_address = addr.address
# 将收集到的信息添加到列表中
for ipv6_addr in ipv6_addresses:
network_info.append([interface, ipv4_address, ipv6_addr, mac_address])
seen_interfaces.add(interface)
return network_info
def copy_selected_value(tree, item_id, column):
"""复制选中的值并弹出提示框"""
value = tree.item(item_id, 'values')[tree['columns'].index(column)]
if column == "IPv6":
value = value.split(" (")[0] # 去掉备注
pyperclip.copy(value)
messagebox.showinfo("提示", f"{column} '{value}' 复制成功!")
def ping_ip(ip_address):
"""在新CMD窗口中对指定IP进行ping操作"""
try:
subprocess.Popen(f"start cmd /k ping {ip_address}", shell=True)
except Exception as e:
messagebox.showerror("错误", f"无法 ping IP 地址: {e}")
def show_context_menu(event, tree):
"""显示右键上下文菜单"""
selected_item = tree.selection()
if selected_item:
column_index = int(tree.identify_column(event.x).replace("#", "")) - 1
ip_address = tree.item(selected_item[0], 'values')[column_index]
context_menu = tk.Menu(root, tearoff=0)
context_menu.add_command(label="Ping", command=lambda: ping_ip(ip_address))
context_menu.post(event.x_root, event.y_root)
def on_tree_item_double_click(event, tree):
"""处理双击事件以复制值"""
selected_item = tree.selection()[0]
column = tree.identify_column(event.x)
column_index = int(column.replace("#", "")) - 1
copy_selected_value(tree, selected_item, tree['columns'][column_index])
def setup_treeview(frame):
"""设置树形视图及其样式"""
columns = ("网络接口名称", "IPv4", "IPv6", "MAC")
tree = ttk.Treeview(frame, columns=columns, show="headings")
# 设置列标题和宽度
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=200 if col == "网络接口名称" else 300, anchor='center')
style = ttk.Style()
style.configure("Treeview", rowheight=25, fieldbackground="white", borderwidth=2, relief="solid")
style.configure("Treeview.Heading", font=('Helvetica', 12, 'bold'), borderwidth=2, relief="solid")
return tree
def show_network_info():
global root # 将root设置为全局变量
root = tk.Tk()
root.title("IP 地址查看器(双击复制)")
frame = ttk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True)
network_info = get_network_info()
interface_tree = setup_treeview(frame)
for info in network_info:
interface_tree.insert("", tk.END, values=info)
# 绑定事件
interface_tree.bind("<Double-1>", lambda event: on_tree_item_double_click(event, interface_tree))
interface_tree.bind("<Button-3>", lambda event: show_context_menu(event, interface_tree))
scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=interface_tree.yview)
interface_tree.configure(yscrollcommand=scrollbar.set)
interface_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 调整窗口大小以适应内容
root.update_idletasks()
row_count = len(network_info)
root.minsize(root.winfo_width(), 25 * row_count + 100)
root.geometry("") # 根据内容动态调整窗口大小
root.mainloop()
if __name__ == "__main__":
show_network_info()