Tkinter程序经Pyinstaller打包后点击下载按钮弹出多余新窗口如何解决
问题修复方案
问题根源
Windows系统下multiprocessing模块默认采用spawn模式创建新进程,新进程启动时会重新导入主脚本文件。PyInstaller打包后的exe运行时,新进程没有正确识别入口约束,会重复执行主窗口初始化逻辑,因此每次启动下载进程都会弹出多余的新窗口。
修复步骤
仅需要修改主入口代码,新增multiprocessing.freeze_support()调用即可,该调用是PyInstaller适配多进程的标准处理逻辑,不会影响PyCharm本地运行效果。
修改后的完整代码如下:
import tkinter as tk from download import download_yv as dyv import multiprocessing class DownloadPage(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.grid() self.download_flag=True self.current_row=0 self.current_rowspan=0 self.label1=tk.Label(self,text='Url:',) self.label1.grid(row=self.current_row,column=0,) self.text1=tk.Entry(self,width=45) self.text1.grid(row=self.current_row,column=1,padx=0,pady=0) self.current_row+=1 self.label2=tk.Label(self,text='Save_Dir:',wraplength=200,) self.label2.grid(row=self.current_row,column=0) self.text2=tk.Entry(self,width=45) self.text2.grid(row=self.current_row,column=1,padx=0,pady=0,) self.current_row+=1 self.label3=tk.Label(self,text='Overwrite:',) self.label3.grid(row=self.current_row,column=0) self.var1=tk.BooleanVar(self) self.var1.set('False') self.menu1=tk.OptionMenu(self,self.var1,'True','False') self.current_rowspan=2 self.menu1.grid(row=self.current_row,column=1,columnspan=2,rowspan=self.current_rowspan,sticky='news') self.current_row+=self.current_rowspan self.label4=tk.Label(self,text='Categorize:') self.label4.grid(row=self.current_row,column=0) self.var2 = tk.BooleanVar(self) self.var2.set(True) self.menu2=tk.OptionMenu(self,self.var2,'True','False') self.menu2.grid(row=self.current_row,column=1,columnspan=2,rowspan=self.current_rowspan,sticky='news') self.current_row+=self.current_rowspan self.current_rowspan=2 self.button1=tk.Button(self,text='download',command=self.download) self.button1.grid(row=self.current_row,column=1,columnspan=2,rowspan=self.current_rowspan,sticky='news') self.current_row+=self.current_rowspan self.button2=tk.Button(self,text='Stop Downloading',command=self.stop_download) self.button2.grid(row=self.current_row,column=1,columnspan=1,) def download(self): var1=self.var1.get() var2=self.var2.get() # print(var1,type(var1),var2,type(var2)) self.download_process=multiprocessing.Process(target=dyv,args=(self.text1.get(),self.text2.get(),var1,var2)) self.download_process.start() def stop_download(self): if self.download_process and self.download_process.is_alive(): self.download_process.terminate() if __name__ == '__main__': # 新增这一行适配PyInstaller打包多进程场景 multiprocessing.freeze_support() root=tk.Tk() app=DownloadPage(root) app.mainloop()
修改完成后重新用PyInstaller打包即可解决多余窗口弹出的问题。
内容的提问来源于stack exchange,提问作者user16954854
相关产品推荐
相关产品推荐

