MATLAB Community

MATLAB, community & more

The GUI way of doing things

While I like to write software for my own pleasure, sometimes I write programs to be used by other people--meaning I have to implement a user interface. I like the input function for asking simple questions of the user. Its syntax is straightforward, but its output clutters the Command Window, allows the user to make mistakes, is annoying for typing long answers (like a file name and location), and most importantly it makes the program feel like the interactive fiction I used to write in BASIC. Fortunately MATLAB comes with a lot of functions that build simple GUIs for asking the user questions.

The most basic of these is the inputdlg function. Instead of just input:

a=input('What kind of Peanut Butter would you like? ','s')

you could use

b=inputdlg('What kind of Peanut Butter would you like?')

inputdlg gui

Of course, this leaves the user with the availability of typing anything! He could say that he wants oranges, which is not a valid option (or at least not at my local Stop & Shop). Unfortunately MATLAB provides dialogs with ways of restricting the user's choices. Each one with its pros and cons.

The listdlg provides the user with a list of options. It's by far the ugliest, and you can see by default the sizing is bad and it crops our question.

c = listdlg('PromptString','What kind of Peanut Butter would you like?',...
                'SelectionMode','single', 'ListString',{'Crunchy','Creamy','Natural','Chocolate'})

default listdlg appearance

Fortunately, there is an easy fix with some additional inputs to listdlg:

c = listdlg('PromptString','What kind of Peanut Butter would you like?',...
                'SelectionMode','single', 'ListString',{'Crunchy','Creamy','Natural','Chocolate'},...
                'Name','Select Peanut Butter','ListSize',[230 130])

listdlg appearance after modification

If you have three or less options, you can go the questdlg route:

d = questdlg('What kind of Peanut Butter would you like?', 'Peanut Butter Selection', ...

questdlg for peanut butters

Finally, you could also use a menu dialog to present one button per choice:

e = menu('What kind of Peanut Butter would you like?',...

menu for peanut butters

As you can see none of these are as pretty as one could make a custom dialog, however they are quite easy to code and useful for programming user interactions. Even more compelling than these general choice dialogs are the ones provided that allow the user to select a file, color, or font. Those will be the topic of another post. You can find more about them here.

  • print


コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。