Showerror不想出现,但是代码似乎没有错误

时间:2020-10-10 12:40:27

标签: python tkinter

我用带有tkinter库的Python创建了一个打开文件对话框应用程序:

class MainForm(Frame):
    def __init__(self,parent):
        Frame.__init__(self,parent)
        self.parent=parent
        self.InitUI()

    def InitUI(self):
        #===============#
        self.frame1=Frame()
        self.frame1.pack(fill=X)
        
        self.lbl=Label(self.frame1,text="File Name")
        self.lbl.pack(side=LEFT,padx=5,pady=5)
       
        #===============#
        self.frame2=Frame()
        self.frame2.pack(fill=BOTH,expand=True)
        
        self.text1_Text=StringVar()
        self.text1=Entry(self.frame2,state=DISABLED,textvariable=self.text1_Text)
        self.text1.pack(side=LEFT,anchor=NW,fill=X,expand=True,padx=5,pady=5)
        
        #===============#
        
        self.frame3=Frame()
        self.frame3.pack(fill=BOTH,expand=True)
           
        self.actBtn1=Button(self.frame3,text="Choose CSV File",command=lambda:[self.open_dialog(),self.open_csv_dataframe()])
        self.actBtn1.pack(side=LEFT,padx=5,pady=5)
        
        self.actBtn2=Button(self.frame3,text="Open",state=DISABLED,command=self.tes_dataframe)
        self.actBtn2.pack(side=RIGHT,padx=5,pady=5)
        
        #===============#
        self.frame4=Frame()
        self.frame4.pack(side=LEFT,anchor=N)
        
        self.lbl2=Label(self.frame4,text="Information")
        self.lbl2.pack(side=LEFT,padx=5,pady=5)     
        
        self.helpBtn=Button(self.frame4,text="How To Use The Program")
        self.helpBtn.pack(side=LEFT,padx=5,pady=5,anchor=N)
        
        self.aboutBtn=Button(self.frame4,text="About Program")
        self.aboutBtn.pack(side=RIGHT,padx=5,pady=5,anchor=N)
        #===============#

    def open_dialog(self):
        global fileName
        try:
            self.fileName=filedialog.askopenfilename(initialdir="/",filetypes=(("Comma-separated values","*.csv"),))
            self.text1_Text.set(self.fileName)     
        except FileNotFoundError:
            showerror("Error","The file is not selected yet")

    def open_csv_dataframe(self):
        if(self.actBtn2['state']==NORMAL):
            self.actBtn2['state']=DISABLED
        else:
            self.actBtn2['state']=NORMAL

    def tes_dataframe(self):
        global df
        data=pd.read_csv(self.text1.get(),sep=",")
        df=pd.DataFrame(data)
        root.destroy()      
    
def on_close():
    close = askokcancel("Close", "Do you want to exit?")
    if close:
        root.destroy()
        sys.exit(1)
     

if __name__=='__main__':
    root=Tk()
    app=MainForm(root)
    root.geometry("400x130+130+130")
    root.resizable(False,False)
    root.title("A Quite Complex File Dialog Form")
    root.protocol("WM_DELETE_WINDOW",  on_close)
    root.mainloop()

     

我编写的代码似乎没有错误,但是当我尝试执行此部分时:

    def open_dialog(self):
        global fileName
        try:
            self.fileName=filedialog.askopenfilename(initialdir="/",filetypes=(("Comma-separated values","*.csv"),))
            self.text1_Text.set(self.fileName)     
        except FileNotFoundError:
            showerror("Error","The file is not selected yet")

我尝试不选择一个csv文件,但是没有显示错误消息。它应该看起来像这样:

An error message should be appeared like this

但是它没有出现,

如何使其显示,我尝试了许多解决方法,但没有结果。

2 个答案:

答案 0 :(得分:1)

有很多方法可以创建错误。许多人更愿意为此使用php bin/magento admin:myuser:createraise

由于您使用了FileNotFoundError以外的其他内容,因此您肯定需要使用assert(errorName),并且当len(self.fileName)= 0时(即未选择文件时),必须使用它。

raise

答案 1 :(得分:1)

如果我正确理解问题,那就是如果您强制使用具有不同扩展名的文件,则希望程序告诉您。因此,您可以使用endswith函数,而不会引发异常。

 def open_dialog(self):
    file = filedialog.askopenfilename(initialdir="/",filetypes=(("Comma-separated values","*.csv"),))

    if file.lower().endswith(('.csv',)):
        self.text1_Text.set(file)
    else:
        msg = "The file is not a csv file."
        messagebox.showwarning(self.master.title(), msg, parent=self)

并将控件移到开头

def tes_dataframe(self):
    global df
    if self.text1.get():
        data=pd.read_csv(self.text1.get(),sep=",")
        df=pd.DataFrame(data)
        root.destroy()
    else:
        msg = "The file field is mandatory."
        messagebox.showwarning(self.master.title(), msg, parent=self)

最后...为什么有那么多的全局变量...您确定需要吗?