When I decide the world needs a completely useless but ridiculously fast command window in Python.

CynthiaCynthia
1 min read
import tkinter as tk
import subprocess
from tkinter import messagebox

# 命令配置字典(可自由扩展)
commands = {
    #"清理临时文件": "rm -rf /tmp/*",  # Linux/Mac
    "清理临时文件": "del /q/f/s %temp%\\*",  # Windows
    "启动Web服务": "python -m http.server",
    "网络诊断": "ping 8.8.8.8",
    #"系统信息": "uname -a",  # Linux/Mac
    "系统信息": "systeminfo",  # Windows
    "ip地址获取": "ipconfig",
}

def run_command(command_key):
    cmd = commands.get(command_key)
    if cmd:
        try:
            # 执行命令并获取输出
            result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, text=True)
            output_text.delete(1.0, tk.END)  # 清空输出框
            output_text.insert(tk.END, f"$ {cmd}\n{result}")
        except subprocess.CalledProcessError as e:
            messagebox.showerror("执行错误", f"命令执行失败:\n{e.output}")
    else:
        messagebox.showwarning("未知命令", "未配置此命令")

# 创建主窗口
root = tk.Tk()
root.title("命令快捷面板 v1.0")
root.geometry("600x600")

# 命令按钮区域
button_frame = tk.Frame(root)
button_frame.pack(pady=10, padx=10, fill=tk.X)

# 动态创建按钮
for i, (name, _) in enumerate(commands.items()):
    btn = tk.Button(button_frame, text=name, width=15, 
                   command=lambda n=name: run_command(n))
    btn.grid(row=i//3, column=i%3, padx=5, pady=5)

# 输出显示区域
output_frame = tk.LabelFrame(root, text="命令输出")
output_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)

output_text = tk.Text(output_frame, wrap=tk.WORD)
output_scroll = tk.Scrollbar(output_frame, command=output_text.yview)
output_text.config(yscrollcommand=output_scroll.set)

output_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
output_scroll.pack(side=tk.RIGHT, fill=tk.Y)

root.mainloop()
0
Subscribe to my newsletter

Read articles from Cynthia directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Cynthia
Cynthia