首页 > 解决方案 > 仅当输入文件格式不正确时才显示错误消息框

问题描述

我目前正在为 GUI 编写一个脚本,用户可以在其中指定输入文件和输出文件夹。此 GUI 输入的过程需要 .csv 文件才能工作。如果输入文件不以 csv 结尾,我有一个错误消息提示,但需要帮助来调整它,以便错误消息框仅在用户选择文件后显示,理想情况下,如果文件在他们单击计算按钮之前显示格式错误。

if not main.sourceFilea.endswith('.csv') :
    messagebox.showerror("Input File Error", "Input Equation File must be a .csv file")      
if not main.sourceFileb.endswith('.csv'):
    messagebox.showerror("Input File Error", "Input Variant File must be a .csv file")
main.mainloop()

作为参考,这是我迄今为止拥有的完整 GUI 脚本。我在这里先向您的帮助表示感谢!

import tkinter 
from tkinter import filedialog
from tkinter import messagebox

main = tkinter.Tk()
main.title('Load Combination Software')
main.geometry("1200x300")
main.sourceFilea = ''
main.sourceFileb = ''
main.eq_num = ''
main.outputfolder = ''

def chooseFilea():
    main.sourceFilea =  filedialog.askopenfilename(parent=main, initialdir= "/", title='Please select input equations')
    pathlabela.config(text=main.sourceFilea)

b_chooseFilea = tkinter.Button(main, text = "Browse", width = 10, height = 1, command = chooseFilea)
b_chooseFilea.place(x = 1050,y = 50)
pathlabela = tkinter.Label(main, bg='white')
pathlabela.place(x=50,y=50,height=25,width=1000)
titlea= tkinter.Label(main, text= 'Select Input Equation File' )
titlea.place(x=50,y=30)

def chooseFileb():
    main.sourceFileb = filedialog.askopenfilename(parent=main, initialdir= "/", title='Please select input variants')
    pathlabelb.config(text=main.sourceFileb)

b_chooseFileb = tkinter.Button(main, text = 'Browse', width = 10, height = 1, command = chooseFileb)
b_chooseFileb.place(x = 1050,y = 100)
pathlabelb = tkinter.Label(main, bg='white')
pathlabelb.place(x=50,y=100,height=25,width=1000)
titleb= tkinter.Label(main, text= "Select Variant Input File" )
titleb.place(x=50,y=80)



def chooseDir():
    main.outputfolder =  filedialog.askdirectory(parent=main, initialdir= "/", title='Please select a directory')
    pathlabelc.config(text=main.outputfolder)

b_outputfolder = tkinter.Button(main, text = "Browse", width = 10, height = 1, command = chooseDir)
b_outputfolder.place(x = 1050,y = 150)
pathlabelc = tkinter.Label(main, bg='white')
pathlabelc.place(x=50,y=150,height=25,width=1000)
titlec= tkinter.Label(main, text= "Select Output Folder" )
titlec.place(x=50,y=130)

b_calc = tkinter.Button(main, text = 'Calculate and Quit', width = 45, height = 5, command=main.destroy)
b_calc.place(x=450,y=200)


if not main.sourceFilea.endswith('.csv') :
    messagebox.showerror("Input File Error", "Input Equation File must be a .csv file")      
if not main.sourceFileb.endswith('.csv'):
    messagebox.showerror("Input File Error", "Input Variant File must be a .csv file")
main.mainloop()

print(main.sourceFilea)
print(main.sourceFileb)
print(main.outputfolder)

标签: pythontkinter

解决方案


推荐阅读