[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox
import subprocess
# 源地址配置
SOURCES = {
"清华源": (
"https://pypi.tuna.tsinghua.edu.cn/simple",
"pypi.tuna.tsinghua.edu.cn"
),
"阿里云": (
"https://mirrors.aliyun.com/pypi/simple",
"mirrors.aliyun.com"
),
"中科大": (
"https://pypi.mirrors.ustc.edu.cn/simple",
"pypi.mirrors.ustc.edu.cn"
),
"豆瓣源": (
"http://pypi.douban.com/simple",
"pypi.douban.com"
),
"恢复官方源": ("", "")
}
def run_cmd(cmd):
"""执行cmd命令"""
try:
subprocess.check_call(cmd, shell=True)
return True
except Exception as e:
return False
def switch_source(name):
"""切换源"""
url, host = SOURCES[name]
if name == "恢复官方源":
# 清空配置
ok1 = run_cmd("pip config unset global.index-url")
ok2 = run_cmd("pip config unset install.trusted-host")
if ok1 and ok2:
messagebox.showinfo("成功", "已恢复为官方源!")
else:
messagebox.showerror("失败", "恢复失败,请以管理员身份运行程序")
else:
# 设置国内源
cmd1 = f'pip config set global.index-url {url}'
cmd2 = f'pip config set install.trusted-host {host}'
ok1 = run_cmd(cmd1)
ok2 = run_cmd(cmd2)
if ok1 and ok2:
messagebox.showinfo("成功", f"已切换至【{name}】")
else:
messagebox.showerror("失败", "切换失败,请以管理员身份运行程序")
def check_current():
"""查看当前源"""
try:
res = subprocess.check_output("pip config list", shell=True, encoding="utf-8")
messagebox.showinfo("当前pip配置", res)
except:
messagebox.showerror("错误", "读取配置失败")
# 主界面
root = tk.Tk()
root.title("PIP 一键换源工具")
root.geometry("640x480")
root.resizable(False, False)
# 标题
tk.Label(root, text="Python PIP 国内源切换工具", font=("微软雅黑", 14)).pack(pady=15)
# 按钮
btn_style = {"width": 20, "height": 2, "font": ("微软雅黑", 10)}
tk.Button(root, text="切换 清华源", **btn_style, command=lambda: switch_source("清华源")).pack(pady=4)
tk.Button(root, text="切换 阿里云", **btn_style, command=lambda: switch_source("阿里云")).pack(pady=4)
tk.Button(root, text="切换 中科大", **btn_style, command=lambda: switch_source("中科大")).pack(pady=4)
tk.Button(root, text="切换 豆瓣源", **btn_style, command=lambda: switch_source("豆瓣源")).pack(pady=4)
tk.Button(root, text="恢复 官方源", **btn_style, command=lambda: switch_source("恢复官方源")).pack(pady=4)
tk.Button(root, text="查看当前配置", **btn_style, command=check_current).pack(pady=8)
root.mainloop()