Message Boards Message Boards

0
|
3428 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Button to import file contents doesn't work

Posted 3 years ago

Consider the following line of code:

Button["Browse", Import[SystemDialogInput["FileOpen"]], Method -> "Queued"]

This make a button labeled as "Browse" that calls for the Import function to open a file.

The "Queued" is needed as described here.

I tried it but no output is produced. Why?

On the other hand, executing just this line of code does import the file content:

Import[SystemDialogInput["FileOpen"]]

So, how do I make my button to output the file content?

Thanks a lot!

POSTED BY: Ehud Behar
3 Replies
Posted 2 years ago

@Rohit Namjoshi thanks a lot!

Well, if the user cancels the browse dialog, this is equivalent to the statement

Import[$Canceled]

Can you think of a way so that my program doesn't return that error when the user cancels the dialog? The only thing I can come up with now is a Switch statement:

If the user completes the Import, than get the values of content. (Assuming that a text string is to be imported)

If, on the other way, the user cancels the dialog, than print the error "You canceled the dialog":

Button["Browse", 
 Switch[content = Import[SystemDialogInput["FileOpen"]],
  Head[content] == String, content, Import[$Canceled], 
  "You canceled the dialog"], Method -> "Queued"]

But this rather produces two errors of the kind

Import: First argument $Canceled is not a valid file, directory, or URL specification.

and besides that the value assigned to content is now $Failed.

Any idea on how to elaborate this?

I am trying to build a sort of a (graphical) user interface inside Mathematica, and that's why this question arises.

POSTED BY: Ehud Behar
Posted 2 years ago

Hi Ehud,

Might be better to check it in a separate function

checkedImport[file_] := If[file === $Canceled, Null, Import[file]]

Button["Browse", content = checkedImport[SystemDialogInput["FileOpen"]], 
 Method -> "Queued"]

If content === Null then the import was cancelled. (Throw/Catch is usually better than a Null check especially if the Null has to be passed/checked up the call stack). You will have to decide how to deal with it in your GUI.

POSTED BY: Rohit Namjoshi
Posted 3 years ago

How about

Button["Browse", content = Import[SystemDialogInput["FileOpen"]], Method -> "Queued"]

content is set to whatever was imported. You should handle the case when the user cancels the dialog and it returns $Canceled.

POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract