pip 换源

from tkinter import Tk, Listbox, Button, Label
import os


class tker(Tk):
    pip_source = {
        "清华大学": "https://pypi.tuna.tsinghua.edu.cn/simple/",
        "阿里云": "http://mirrors.aliyun.com/pypi/simple/",
        "中国科技大学": "https://pypi.mirrors.ustc.edu.cn/simple/",
        "豆瓣": "http://pypi.douban.com/simple/",
        "中国科学技术大学": "http://pypi.mirrors.ustc.edu.cn/simple/",
    }

    def setui(self):
        self.geometry("300x500")

        self.bt1 = Button(self, text="点击更换PIP源", command=self.on_bt1_click)
        self.bt1.pack()

        self.lbox1 = Listbox(self)
        for item in reversed(list(self.pip_source.keys())):
            self.lbox1.insert(0, item)

        self.lbox1.pack(expand=True, fill="both")

        self.info = Label(self)
        self.info.pack()

        self.msg("pip 更换国内源")
        return self

    def clear_info(self):
        self.info["text"] = ""

    def msg(self, m: str, sec: float = 0):
        tt = round(sec * 1000)
        self.info["text"] = str(m)
        if tt > 0:
            self.info.after(tt, self.clear_info)

    def on_bt1_click(self):
        cs = self.lbox1.curselection()

        if cs:
            item = self.lbox1.get(cs[0])
            text = ["[global]", "index-url = " + self.pip_source[item]]

            pip_path = os.path.join(os.path.expanduser("~"), "pip")

            if not os.path.exists(pip_path):
                os.mkdir(pip_path)

            with open(os.path.join(pip_path, "pip.ini"), "w", encoding="utf8") as f:
                f.write("\n".join(text))
                self.msg("pip已经更换为: " + item, 5)


if __name__ == "__main__":
    tker().setui().mainloop()
posted @ 2024-07-03 01:20  方头狮  阅读(23)  评论(0编辑  收藏  举报