0

我有以下文件上传代码。我想为两件事修改这段代码: 1.如果用户取消 askopenfilenames 命令,整个程序将停止。2.如果用户没有选择所需的文件数,文件上传功能将重新启动,直到选择正确的文件数。

import Tkinter
from Tkinter import Tk
tk=Tk()
from tkFileDialog import askopenfilenames
import tkMessageBox
def fileupload():
     tk.withdraw()
     uploadedfiles = askopenfilenames(multiple=True)
     ##if user cancels: (IF STATEMENT TO RESULT IN MESSAGEBOX AND CODE TO STOP)
      ###tk.withdraw()
      ###tkMessageBox.showinfo(message="File Upload has been cancelled program will stop")
       ##Stop code

    if len(uploadedfiles)>2 or len(uploadedfiles)<2:
       tk.withdraw()
       tkMessageBox.showinfo(message="2 files have not been selected!")
       ##rerun function to reselect files
   return uploadedfiles
uploadedfiles=fileupload()
print uploadedfiles
4

1 回答 1

1

首先检查返回的字符串askopenfilenames是否为空,表示用户关闭了对话框。然后使用tk.splitlist从字符串创建一个列表(如果它不为空)并检查它的长度:

tk=Tk()
tk.withdraw()

def fileupload():
    while True:
        uploadedfilenames = askopenfilenames(multiple=True)
        if uploadedfilenames == '':
            tkMessageBox.showinfo(message="File Upload has been cancelled program will stop")
            return
        uploadedfiles = tk.splitlist(uploadedfilenames)
        if len(uploadedfiles)!=2:
           tkMessageBox.showinfo(message="2 files have not been selected!")
        else:
            return uploadedfiles

print fileupload()
于 2013-06-07T01:45:39.747 回答