buttonGe.grid(row=8, column=5, pady=2) buttonHe.grid(row=9, column=5, pady=2) buttonIe.grid(row=10, column=5, pady=2) buttonAf = Button(root, fg="Orange", text="3") buttonBf = Button(root, fg="Orange", text="1") buttonCf = Button(root, fg="Orange", text=" ") buttonDf = Button(root, fg="Green", text="9") buttonEf = Button(root, fg="Green", text=" ") buttonFf = Button(root, fg="Green", text="3") buttonGf = Button(root, fg="Orange", text="6") buttonHf = Button(root, fg="Orange", text="2") buttonIf = Button(root, fg="Orange", text="8") buttonIf.config(height=50, width=50) buttonAf.grid(row=2, column=6, pady=2) buttonBf.grid(row=3, column=6, pady=2) buttonCf.grid(row=4, column=6, pady=2) buttonDf.grid(row=5, column=6, pady=2) buttonEf.grid(row=6, column=6, pady=2) buttonFf.grid(row=7, column=6, pady=2) buttonGf.grid(row=8, column=6, pady=2) buttonHf.grid(row=9, column=6, pady=2) buttonIf.grid(row=10, column=6, pady=2) buttonAg = Button(root, fg="Orange", text="3") buttonBg = Button(root, fg="Orange", text="5") buttonCg = Button(root, fg="Orange", text=" ") buttonDg = Button(root, fg="Green", text="8")
class Sample(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.resizable(0, 0) self.geometry('420x700+300+100') self.title('Mac OSX Button Testing') self.wm_attributes('-modified', 1) self.main_color = ColorVar(value='#ffe6f4') self['bg'] = self.main_color grid(self, 25, 5) self.L1 = tk.Label(self, text='Comparison', bg=self.main_color, font=('', 18, 'bold')) self.L1.grid(row=0, column=0, columnspan=5, sticky='nsew') Button(self, text='Hello').grid(row=1, column=1, sticky='s') ttk.Button(self, text='Hello').grid(row=1, column=3, sticky='s') tk.Button(self, text='Hello').grid(row=1, column=2, sticky='s') tk.Label(self, bg=self.main_color, font=('', 10), text='(Mac OSX)').grid(row=2, column=1, sticky='n',) tk.Label(self, bg=self.main_color, font=('', 10), text='(ttk themed)').grid(row=2, column=3, sticky='n') tk.Label(self, bg=self.main_color, font=('', 10), text='(Default)').grid(row=2, column=2, sticky='n') ttk.Separator(self, orient='vertical').grid( row=3, column=0, columnspan=5, sticky='ew') # ------------ Seperator ------------- # ------------ Demonstration ------------ self.sfr = SFrame(self, bg=self.main_color) self.sfr.grid(rowspan=27, columnspan=5, sticky='nsew') for i in range(5): self.sfr.grid_columnconfigure(i, weight=1) self.L2 = tk.Label(self.sfr, text='Demonstration', bg=self.main_color, font=('', 20, 'bold')) self.L2.grid(row=1, column=0, columnspan=5, sticky='new', pady=(20, 10)) # ------------ Active Color ------------ self.L3 = tk.Label(self.sfr, text='1. Change Active color', bg=self.main_color, font=('', 15, 'bold')) self.L3.grid(row=2, column=0, columnspan=5, sticky='nsew', pady=10) self.L4 = tk.Label(self.sfr, text='The active color can be changed to any gradient color.', bg=self.main_color, font=('', 10)) self.L4.grid(row=3, column=0, columnspan=5, sticky='new') self.B1 = Button(self.sfr, text='Press Me', pady=20) self.B1.grid(row=4, column=0, columnspan=5, pady=20) self.C1 = tk.StringVar(value='Select') self.L5 = tk.Label(self.sfr, text='From', bg=self.main_color, font=('', 12)) self.L5.grid(row=5, column=1, sticky='ew') self.L6 = tk.Label(self.sfr, text='To', bg=self.main_color, font=('', 12)) self.L6.grid(row=5, column=3, sticky='ew') button_container1 = tk.Frame(self.sfr, bg=self.main_color) button_container1.grid(row=6, column=0, columnspan=5, sticky='ew', pady=10, padx=10) button_container1.columnconfigure(0, weight=1) button_container1.columnconfigure(1, weight=1) self.Om1_b = Button(button_container1, text='Change Color', bg='#d0c0ea', borderless=1) self.Om1_b.grid(row=0, column=0, padx=(0, 2), sticky='ew') self.Om2_b = Button(button_container1, text='Change Color', bg="#d0c0ea", borderless=1) self.Om2_b.grid(row=0, column=1, sticky='ew') self.Om1_b['command'] = lambda: self.change_active_color(1) self.Om2_b['command'] = lambda: self.change_active_color(2) # ------------ Background Color ------------ self.L7 = tk.Label(self.sfr, text='2. Change Background color', bg=self.main_color, font=('', 15, 'bold')) self.L7.grid(row=7, column=0, columnspan=5, sticky='nsew', pady=(50, 0)) self.L8 = tk.Label(self.sfr, text='Click on the button to choose the color.', bg=self.main_color, font=('', 10)) self.L8.grid(row=8, column=0, columnspan=5, sticky='new', pady=10) self.B2 = Button(self.sfr, text='Color me', font=('', 30,), pady=10) self.B2.grid(row=9, column=0, columnspan=5, sticky='', pady=20) button_container2 = tk.Frame(self.sfr, bg=self.main_color) button_container2.grid(row=10, column=0, columnspan=5, sticky='ew', pady=10, padx=10) button_container2.columnconfigure(0, weight=1) button_container2.columnconfigure(1, weight=1) self.B3 = Button(button_container2, text='Change Background Color', bg='#d0c0ea', borderless=1) self.B3['command'] = lambda: self.B2.config(bg=askcolor()[1]) self.B3.grid(row=0, column=0, padx=(0, 2)) self.B4 = Button(button_container2, text='Change Foreground Color', bg="#d0c0ea", borderless=1) self.B4['command'] = lambda: self.B2.config(fg=askcolor()[1]) self.B4.grid(row=0, column=1) # ------------ Borderless ------------ self.L9 = tk.Label(self.sfr, text='3. Switch Between Borderless', bg=self.main_color, font=('', 15, 'bold')) self.L9.grid(row=11, column=0, columnspan=5, sticky='sew', pady=(50, 0)) self.L10 = tk.Label(self.sfr, text=""" In borderless it will blend with its parent widget background color. Give parameter `borderless = True / False` to use it.""", bg=self.main_color, font=('', 10)) self.L10.grid(row=12, column=0, columnspan=5, sticky='new') self.B5 = Button(self.sfr, text='No Borders', borderless=1, height=40, bg='#212F3D', fg='white', activebackground=("#EAECEE", "#212F3D")) self.B5.grid(row=13, columnspan=5, pady=(20, 5)) self.B6 = Button(self.sfr, text='No Borders', borderless=1, height=40, bg='#F7DC6F', fg='#21618C', activebackground=('#B3B6B7', '#58D68D')) self.B6.grid(row=14, columnspan=5, pady=(0, 20)) self.var1 = tk.BooleanVar(value=True) self.CB1 = tk.Checkbutton(self.sfr, text='Toggle Borderless', variable=self.var1, bg=self.main_color, command=self.change_borderless_state) self.CB1.grid(row=15, columnspan=5, pady=(0, 10)) # ------------ Bordercolor ------------ self.L11 = tk.Label(self.sfr, text='4. Change Bordercolor', bg=self.main_color, font=('', 15, 'bold')) self.L11.grid(row=16, column=0, columnspan=5, sticky='sew', pady=(50, 0)) self.L12 = tk.Label(self.sfr, text="Change Bordercolor of the button\nNote: if borderless=True, then the bordercolor won't work.", bg=self.main_color, font=('', 10)) self.L12.grid(row=17, column=0, columnspan=5, sticky='new') self.B7 = Button(self.sfr, text='Button', pady=10, padx=5, font=('Zapfino', 12, 'bold')) self.B7.grid(row=18, columnspan=5, pady=30) self.CS1 = Colorscale(self.sfr, value='hex', mousewheel=1, command=lambda e: self.B7.config(bordercolor=e)) self.CS1.grid(row=19, columnspan=5, sticky='ew', padx=10) self.CS2 = Colorscale(self.sfr, value='hex', mousewheel=1, gradient=('#FCF6F5', '#990011'), command=lambda e: self.B7.config(bg=e)) self.CS2.grid(row=20, columnspan=5, sticky='ew', padx=10, pady=5) self.CS3 = Colorscale(self.sfr, value='hex', mousewheel=1, gradient=('green', 'yellow'), command=lambda e: self.B7.config(fg=e)) self.CS3.grid(row=21, columnspan=5, sticky='ew', padx=10) self.CS4 = Colorscale(self.sfr, value='hex', mousewheel=1, gradient=('pink', 'purple'), command=lambda e: self.B7.config(overforeground=e)) self.CS4.grid(row=22, columnspan=5, sticky='ew', padx=10, pady=5) # ------------ Random button styling ------------ self.L11 = tk.Label(self.sfr, text='5. Button Styling', bg=self.main_color, font=('', 15, 'bold')) self.L11.grid(row=23, column=0, columnspan=5, sticky='sew', pady=(50, 0)) self.L12 = tk.Label(self.sfr, text="Press the button to ramdomise the style of the button.", bg=self.main_color, font=('', 10)) self.L12.grid(row=24, column=0, columnspan=5, sticky='new') self.B10 = Button(self.sfr, text='Button', borderless=1) self.B10.grid(row=25, columnspan=5, pady=20) self.B11 = Button(self.sfr, text='Change Style', borderless=1, fg='#21618C', activebackground=('#B3B6B7', '#58D68D'), command=self.change_button_style) self.B11.grid(row=26, columnspan=5, ipady=5) self.button_clicks = 1 self.Text1 = tk.Text(self.sfr, background=self.main_color, highlightthickness=0, relief='sunken', height=20, bd=2, padx=10) self.Text1.grid(row=27, columnspan=5, pady=20, padx=20) self.sfr._avoid_mousewheel( (self.Text1, self.CS1, self.CS2, self.CS3, self.CS4)) self.change_button_style() self.update_idletasks() def change_active_color(self, num): hexcode = askcolor()[1] if num == 1: self.Om1_b['bg'] = self.Om1_b['text'] = hexcode self.Om1_b['fg'] = check_light_dark(hexcode) else: self.Om2_b['bg'] = self.Om2_b['text'] = hexcode self.Om2_b['fg'] = check_light_dark(hexcode) self.B1['activebackground'] = (self.Om1_b['bg'], self.Om2_b['bg']) def change_borderless_state(self): if self.var1.get(): self.B5['borderless'] = 1 self.B6['borderless'] = 1 else: self.B5['borderless'] = 0 self.B6['borderless'] = 0 def change_button_style(self): cnf = dict( foreground=get_random_colors(), background=get_random_colors(), activebackground=get_random_colors(2), activeforeground=get_random_colors(), overrelief=get_random_relief(), relief=get_random_relief(), highlightthickness=get_random_size(1, 1, 5), borderwidth=get_random_size(1, 1, 5), font=get_random_font(), highlightbackground=get_random_colors(), focuscolor=get_random_colors(), overbackground=get_random_colors(), overforeground=get_random_colors(), ) self.B10.config(**cnf) self.Text1.insert('end', '\n\nBUTTON STYLE %s\n\n' % self.button_clicks) for k, v in cnf.items(): if k == 'font': self.Text1.insert('end', 'font:\n') for i, j in v.config().items(): self.Text1.insert('end', '\t%s\t\t= %s\n' % (i, j)) else: self.Text1.insert('end', '%s\t\t\t= %s\n' % (k, v)) self.Text1.see('end') self.Text1.insert('end', '\n\n'+'-'*40) self.button_clicks += 1 self.sfr['canvas'].yview_moveto('1.0') self.update_idletasks()
class Application(tk.Tk): def __init__(self): super().__init__() self.name = "" self.version = "V3.2.2" self.sampling_rate_ver = tk.IntVar() self.content = tk.StringVar() self.update_url = tk.StringVar() self.update_info = tk.StringVar() self.read_url = "" self.read_str = tk.StringVar() self.lock = threading.Lock() # 创建一个顶级弹窗 self.withdraw() self.top = tk.Toplevel() self.top.title("请勿关闭") if sys.platform[:3] == "win": self.top.iconbitmap("logo.ico") self.top.attributes("-alpha", 0.99) def close_fun(): ans = messagebox.askokcancel(title="警告", message="首次使用需要网络,确定要关闭吗?") if ans: self.top.destroy() self.destroy() self.top.protocol("WM_DELETE_WINDOW", close_fun) # 设置窗口大小 width = 301 height = 169 # 获取屏幕尺寸以计算布局参数,使窗口居于屏幕中央 screenwidth = self.top.winfo_screenwidth() screenheight = self.top.winfo_screenheight() geometry_str = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 3) self.top.geometry(geometry_str) self.top.resizable(width=False, height=False) tk.Label( self.top, text="首次使用会自动下载一些工具文件,可\r\n能需要等待一分钟左右,过程中请保持\r\n网络正常连接,请稍等。。。。。。", wraplength=280, justify="left", font=("宋体", 12), fg="red").pack(pady=10) self.downBar = ttk.Progressbar(self.top, length=110, mode="determinate") self.downBar.pack(fill=tk.X, padx=25, pady=15) self.top.withdraw() # 创建 t2 = threading.Thread(target=self.init_fun) # 守护 !!! t2.setDaemon(True) # 启动 t2.start() self.createWidgets() def init_fun(self): # 创建输出文件夹 mkdir("WAV/") # print("开始下载ffmpeg包") if sys.platform[:3] == "win": ffmpeg_file_name = "ffmpeg.exe" is_64bits = sys.maxsize > 2**32 if is_64bits: ffmpeg_file_url = "https://ncstatic.clewm.net/rsrc/2020/1030/13/7b83b0086583af8a79637e995807b964.obj" else: ffmpeg_file_url = "https://ncstatic.clewm.net/rsrc/2020/0920/08/67baff128cddba3d1104b7be2f9f84fa.obj" if sys.platform == "darwin": ffmpeg_file_name = "ffmpeg" ffmpeg_file_url = "https://ghproxy.com/https://evermeet.cx/ffmpeg/get" if not os.path.exists(ffmpeg_file_name): self.top.deiconify() try: str_out = [ './aria2c', '--check-certificate=false', '-x', '8', '-o', "ffmpeg.7z", ffmpeg_file_url ] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) for line in process.stdout: # print(line) status_res = re.search(r'\((?P<status>[\s\S]*?)\):', line) if status_res is not None: if status_res.groupdict()['status'] == "ERR": raise Exception("下载错误") percent_res = re.search(r'\((?P<percent>[\s\S]*?)%\)', line) if percent_res is not None: progress = percent_res.groupdict()['percent'] print(progress) self.downBar["value"] = progress self.top.update() process.wait() if process.poll() == 0: # 解压文件 str_out = ['./7z', 'x', "ffmpeg.7z"] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process_1 = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process_1 = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) process_1.wait() if process_1.poll() == 0: for item_7z in glob.glob("ffmpeg*.7z"): os.remove(item_7z) if sys.platform == "darwin": os.chmod("./ffmpeg", 0o755) print("解压完成") self.downBar["value"] = 110 self.top.destroy() self.deiconify() except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.top.withdraw() messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试(首次使用需要网络)") self.top.destroy() self.destroy() else: self.top.destroy() self.deiconify() def createWidgets(self): self.title("嗖音HOME " + self.version[1:] + " - 独居者") if sys.platform[:3] == "win": self.iconbitmap("logo.ico") self.attributes("-alpha", 0.99) # 设置颜色 progress_color = "#1E94A0" progress_chunk_color = "#FA7268" declare_color = "red" update_color = "#F9425B" update_bg_color = "#0071CF" font_color = "#EBE5D9" btn_color = "#14B09B" frame_color = "#0359AE" # 设置字体 if sys.platform[:3] == "win": l_font = ("宋体", 12) m_font = ("宋体", 11) s_font = ("宋体", 9) if sys.platform == "darwin": l_font = ("宋体", 16) m_font = ("宋体", 15) s_font = ("宋体", 12) # 设置窗口大小 width = 603 height = 339 # 获取屏幕尺寸以计算布局参数,使窗口居于屏幕中央 screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight() geometry_str = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 3) self.geometry(geometry_str) self.resizable(width=False, height=False) L_frame = tk.Frame(width=373, height=height, bg=frame_color) R_frame = tk.Frame(width=230, height=height, bg=frame_color) L_frame.grid(row=0, column=0) R_frame.grid(row=0, column=1) self.update_info.set("检测更新中......") # 创建 t = threading.Thread(target=self.update_fun) read_t = threading.Thread(target=self.read_fun) # 守护 !!! t.setDaemon(True) read_t.setDaemon(True) # 启动 t.start() read_t.start() # 右边开始布局 updateLab = tk.Label(R_frame, textvariable=self.update_info, font=l_font, bg=update_bg_color, fg=update_color) updateLab.place(x=0, y=0, width=230, height=25) updateLab.bind("<Button-1>", self.open_browser) if sys.platform[:3] == "win": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color) if sys.platform == "darwin": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color, highlightthickness=0) self.text.place(x=30, y=50, width=170, height=155) self.text.insert(tk.INSERT, "有什么想对开发者说的可以说") self.text.bind("<Button-1>", self.del_show) if sys.platform[:3] == "win": buttonSend = tk.Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonSend = Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonSend.place(x=65, y=230, width=101, height=30) declare_str = "声明:仅供个人录制音频转换使用" labDeclare = tk.Label(R_frame, text=declare_str, wraplength=151, justify="left", font=s_font, bd=1, relief="solid", bg=frame_color, fg=declare_color) labDeclare.place(x=40, y=282, width=151, height=41) # 左边开始布局 self.read_str.set("随机阅读:正在加载中......") labShow = tk.Label(L_frame, textvariable=self.read_str, wraplength=252, justify="left", anchor="w", padx=5, bd=1, relief="solid", bg=frame_color, fg=font_color) labShow.place(x=30, y=25, width=313, height=70) labReadAll = tk.Label(L_frame, text="查看全文", bg=frame_color, fg="#22B14C") labReadAll.place(x=287, y=26, width=55, height=68) labReadAll.bind("<Button-1>", self.read_page) self.content.set("请选择要转换的音频文件") lab = tk.Label(L_frame, textvariable=self.content, font=m_font, bg=frame_color, fg=font_color) lab.place(x=30, y=110, width=313, height=20) if sys.platform[:3] == "win": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color) if sys.platform == "darwin": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color, highlightthickness=0) self.entry_url.place(x=30, y=160, width=238, height=30) self.entry_url.insert(0, "请输入分享链接即可") if sys.platform[:3] == "win": self.buttonOpenUrl = tk.Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonOpenUrl = Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonOpenUrl.place(x=268, y=160, width=75, height=30) if sys.platform[:3] == "win": self.buttonStart = tk.Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonStart = Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonStart.place(x=268, y=200, width=75, height=30) if sys.platform[:3] == "win": buttonOpen = tk.Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonOpen = Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonOpen.place(x=110, y=200, width=101, height=30) labOut = tk.Label(L_frame, text="输出配置:", justify="left", font=m_font, bg=frame_color, fg=font_color) labOut.place(x=30, y=250, width=75, height=30) buttonVer = tk.Checkbutton(L_frame, text="旧版", font=m_font, variable=self.sampling_rate_ver, bg=frame_color, fg=font_color, activeforeground=font_color, activebackground=frame_color, selectcolor=frame_color) buttonVer.place(x=110, y=250, width=71, height=30) if sys.platform[:3] == "win": buttonFile = tk.Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonFile = Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonFile.place(x=268, y=291, width=75, height=23) labHelp = tk.Label(L_frame, text="<使用指南>", font=s_font, bg=frame_color, fg=font_color) labHelp.place(x=10, y=306, width=75, height=23) labHelp.bind("<Button-1>", self.show_help) progressbar_style = ttk.Style() progressbar_style.theme_use('alt') progressbar_style.configure("blue.Vertical.TProgressbar", troughcolor=progress_color, background=progress_chunk_color, troughrelief="flat") self.progressBar = ttk.Progressbar(self, style="blue.Vertical.TProgressbar", length=115, mode="determinate", orient="vertical") self.progressBar.place(x=368, y=0, width=5, height=height) # 反馈信息发送函数,具体实现可以自定义,钉钉机器人和与你机器人均可 # 钉钉机器人文档:https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi # 与你机器人文档:http://www.uneed.com/openapi/pages/index.html#/chatbot/intro def send_message(self): try: # print(self.text.get("1.0", "end").strip('\n')) msg = self.text.get("1.0", "end").strip('\n') if msg == "" or msg == "有什么想对开发者说的可以说": messagebox.showwarning(title="警告", message="请输入内容后发送") return ret_message = send_ding_msg(msg) if ret_message[0] == "showinfo": messagebox.showinfo(title=ret_message[1], message=ret_message[2]) if ret_message[0] == "showwarning": messagebox.showwarning(title=ret_message[1], message=ret_message[2]) if ret_message[0] == "showerror": messagebox.showerror(title=ret_message[1], message=ret_message[2]) except Exception as e: print("网络未连接,请检查连接后重试") print(e) messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试") def del_show(self, event): print(event) self.text.delete("1.0", "end") def del_url_show(self): self.entry_url.delete(0, "end") def urlfile_thread(self, music_url): self.lock.acquire() try: self.content.set("请选择要转换的音频文件") try: music_data = Amusic.get_all_music_parm(music_url) if music_data[0] == "null" and music_data[1] == "null": print("不支持此分享链接或者链接格式错误") messagebox.showwarning(title="警告", message="不支持此分享链接或者链接格式错误") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return if music_data[1] == "null": music_name = music_data[0] self.content.set(music_name) messagebox.showwarning(title="警告", message=music_name) # 恢复本地转换按钮 self.buttonStart.config(state="normal") return music_name = music_data[0] music_play_url = music_data[1] except Exception as e: print("网络未连接,请检查连接后重试") print(e) messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return self.content.set(music_name) start_time = time.perf_counter() sampling_rate = "48000" if self.sampling_rate_ver.get() == 1: sampling_rate = "32000" self.ffmpeg_run(music_play_url, music_name, sampling_rate) elapsed = (time.perf_counter() - start_time) print("耗时:%6.2f" % elapsed + "秒") self.content.set("耗时:%6.2f" % elapsed + "秒") finally: self.lock.release() # 恢复本地转换按钮 self.buttonStart.config(state="normal") def urlfile_convert(self): # 禁用本地转换按钮 self.buttonStart.config(state="disabled") music_url = self.entry_url.get() if music_url == "" or music_url == "请输入分享链接即可": messagebox.showwarning(title="警告", message="请输入分享链接后执行") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return if not self.lock.locked(): temp_thread = threading.Thread(target=self.urlfile_thread, args=(music_url, )) temp_thread.setDaemon(True) temp_thread.start() def openfile(self): # print("文本框内容:" + entry_url.get()) file_path = filedialog.askopenfilename(title="选择音频文件") filename = os.path.basename(file_path) self.name = file_path print(self.name) self.content.set(filename) def ffmpeg_run(self, input_file, music_name, sampling_rate): self.progressBar["value"] = 0 self.update() temp_path = "TEMP/" mkdir(temp_path) temp_music_name = str(round(time.time() * 1000)) str_out = [ './ffmpeg', '-i', input_file, '-ar', sampling_rate, '-ac', '1', '-acodec', 'pcm_s16le', '-hide_banner', temp_path + temp_music_name + ".wav" ] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) for line in process.stdout: # print(line) duration_res = re.search(r'\sDuration: (?P<duration>\S+)', line) if duration_res is not None: duration = duration_res.groupdict()['duration'] duration = re.sub(r',', '', duration) result = re.search(r'\stime=(?P<time>\S+)', line) if result is not None: elapsed_time = result.groupdict()['time'] progress = (get_seconds(elapsed_time) / get_seconds(duration)) * 100 print(elapsed_time) print(progress) # self.content.set("进度:%3.2f" % progress + "%") self.progressBar["value"] = progress self.update() process.wait() if process.poll() == 0: infile_path = temp_path + temp_music_name + ".wav" outfile_path = "WAV/" + music_name + ".wav" del_wavparm(infile_path) shutil.move(infile_path, outfile_path) del_file(temp_path) print("success:", process) # 设置终点 self.progressBar["value"] = 115 else: print("error:", process) def localfile_thread(self): self.lock.acquire() try: start_time = time.perf_counter() sampling_rate = "48000" if self.sampling_rate_ver.get() == 1: sampling_rate = "32000" music_name = os.path.splitext(os.path.basename(self.name))[0] self.ffmpeg_run(self.name, music_name, sampling_rate) elapsed = (time.perf_counter() - start_time) print("耗时:%6.2f" % elapsed + "秒") self.content.set("耗时:%6.2f" % elapsed + "秒") finally: self.lock.release() # 恢复网络转换按钮 self.buttonOpenUrl.config(state="normal") def localfile_convert(self): # 禁用网络转换按钮 self.buttonOpenUrl.config(state="disabled") if not self.name: messagebox.showwarning(title="警告", message="请先选择文件后执行") # 恢复网络转换按钮 self.buttonOpenUrl.config(state="normal") return if not self.lock.locked(): temp_thread = threading.Thread(target=self.localfile_thread) temp_thread.setDaemon(True) temp_thread.start() def open_browser(self, event): print(event) open_url = self.update_url.get() if open_url != "": webbrowser.open(open_url) def read_fun(self): pre_url = "https://blog.csdn.net/qq_41730930" try: read_data_url = "https://cdn.jsdelivr.net/gh/space9bug/sharesoftware@master/s/articles.json" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36' } response = requests.request("GET", read_data_url, headers=headers) response.encoding = "utf-8" response_code = response.status_code if response_code == 200: read_data = json.loads(response.text) if read_data is not None: read_index = random.randint(0, len(read_data) - 1) article_title = read_data[read_index][0] if article_title is not None: self.read_str.set("随机阅读:" + article_title) article_url = read_data[read_index][1] if article_url is not None: if re.match(r"^\d*$", article_url) is None: self.read_url = article_url else: self.read_url = pre_url + "/article/details/" + article_url else: self.read_url = pre_url else: self.read_url = pre_url else: self.read_url = pre_url except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.read_url = pre_url def read_page(self, event): print(event) if self.read_url != "": webbrowser.open(self.read_url) def show_help(self, event): print(event) self.update() # 获取主窗口的左上角坐标 origin_x = self.winfo_x() origin_y = self.winfo_y() # 获取主窗口的宽、高 origin_width = self.winfo_width() origin_height = self.winfo_height() # 设置窗口大小 width = 300 height = 169 # 创建一个顶级弹窗 helpTop = tk.Toplevel() helpTop.title("使用指南") if sys.platform[:3] == "win": helpTop.iconbitmap("logo.ico") helpTop.attributes("-alpha", 0.99) geometry_str = '%dx%d+%d+%d' % (width, height, origin_x + (origin_width - width) / 2, origin_y + (origin_height - height) / 2) helpTop.geometry(geometry_str) helpTop.resizable(width=False, height=False) helpTop.focus_set() help_str = "使用指南\n1.本地音频转换:打开选择本地文件,开始进行转换\n2.网络分享音频:支持唱鸭、全民K歌、唱吧、荔枝、喜马拉雅、斗歌、酷狗唱唱、猫爪弹唱、弹唱达人、爱唱、闪歌、VV音乐、爱听、酷狗音乐大字版、酷我K歌、全民K诗、天籁K歌、咪咕K歌、酷狗K歌" helpMessage = tk.Message(helpTop, text=help_str, justify="left", width=260) helpMessage.place(x=0, y=0, width=300, height=169) def update_fun(self): try: url = "https://cdn.jsdelivr.net/gh/space9bug/sharesoftware@master/s/version.json" # 因为jsDelivr缓存更新时间为24小时,所以推迟版本更新检测。 release_time = "2021-02-27 15:30" hours = (time.mktime(time.strptime(release_time, "%Y-%m-%d %H:%M")) - round(time.time())) // 3600 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36' } response = requests.request("GET", url, headers=headers) print(response.text) version_data = json.loads(response.text) latest_version = version_data["latestVersion"] if hours >= 24 and self.version != latest_version: print(version_data["downUrl"]) self.update_info.set(version_data["info"]) self.update_url.set(version_data["downUrl"]) messagebox.showinfo(title="更新提醒:" + self.version, message="新的更新来啦,为了您有更好的体验,建议您点击界面右上角进行更新。") else: self.update_info.set("已是最新版本:" + self.version) self.update_url.set(version_data["downUrl"]) # burying_point() except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.update_info.set("已是最新版本:" + self.version)