Introduction to Zenity (Part 2)

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
348
Reaction score
390
Credits
12,246
This article is the rest of the information on using Zenity.

Zenity is a command-line utility for Linux and Unix-like operating systems that allows you to create graphical dialog boxes and forms from shell scripts or command-line prompts.

If you have not read the first part, then look at it now at Introduction to Zenity (Part 1).

Progress

Displays a progress bar during commands being executed to allow for the user to see that something is being done as well and the progress that the script has left to finish.

The syntax for the '--progress' parameter is:

--progress Display progress indication dialog
--text=TEXT Set the dialog text
--percentage=PERCENTAGE Set initial percentage
--pulsate Pulsate progress bar
--auto-close Dismiss the dialog when 100% has been reached
--auto-kill Kill parent process if Cancel button is pressed
--no-cancel Hide Cancel button
--time-remaining Estimate when progress will reach 100%


The '--percentage' parameter sets the initial value of the progress bar. This usually may be '0'.

The '--pulsate' parameter just causes a small part of the bar to be red and move back and forth across the bar as a whole. It does not mark a width of the bar to show a percentage. The parameter is only good if using the '--time-remaining' parameter.

If you do not want a 'Cancel' button as an option when it shows the progress bar, then use '--no-cancel' parameter. If you do leave the 'Cancel' button, then use the '--auto-kill' parameter. When used, it stops the process as soon as the 'Cancel' button is pressed.

If you want the Zenity box to close when the percentage reaches 100%, then use the '--auto-close' parameter. If not used, the user must press the 'OK' button when the process is completed to close the box.

The '--percent' parameter sets the initial percentage to begin the process. Usually, this is '0', but some circumstances may require a different starting point.

So, let's look at an example:

(
# ==========================================================
echo "# Running First Task." ; sleep 2
# Command for first task goes on this line.
# ==========================================================
echo "20"
echo "# Running Second Task." ; sleep 2
# Command for second task goes on this line.
# ===========================================================
echo "40"
echo "# Running Third Task." ; sleep 2
# Command for third task goes on this line.
# ===========================================================
echo "60"
echo "# Running Fourth Task." ; sleep 2
# Command for fourth task goes on this line.
# ============================================================
echo "80"
echo "# Running Fifth Task." ; sleep 2
# Command for fifth task goes on this line.
# ============================================================
echo "99"
# All Finished
echo "# All finished."
sleep 2
echo "100"
echo "# Done") |
zenity --progress --title="Progress Status" --text="First Task" --percentage=0 --auto-kill --auto-close


We have a large set of instructions in parentheses that are being piped into the Zenity command. Let's look at the Zenity command first. It is, of course, a progress bar with the title of 'Progress Status'. The initial text is 'First Task'. We start the percentage count at '0'. If you select 'Cancel', the script will end (--auto-kill). Once the percentage reaches 100%, '--auto-close', the window is closed. Be aware, as soon as you issue the statement that the percentage is '100', the window closes and the Zenity command ends. I show the initial start of the GUI in Figure 1.

Figure 1.JPG

FIGURE 1

The commands being piped into the Zenity command are split into 6 sections. Each section is based on 20% of the whole progress. The last section is when the commands are all completed and it changes the progress to 100%, causing the Zenity command to end.

NOTE: It may be best to use 99% at the last set of commands, then issue the 100% mark at the end of the list, especially when using '--auto-close'.

Each section starts with the statement that echos a percentage value. The line following that statement is another echo statement. Here, each string being echoed starts with a pound sign. The pound sign is important. The string is taken in by Zenity, as well as the previous line. It updates the information, the percentage and text. The pound sign causes the window information to be updated. After these two lines for Zenity, you can add in all the commands you need for the section. You can change the percentage values as you need as well as the text for the Zenity box. Be sure to leave in the pound sign.

The last section shows I update the percentage info and the percent is '99'. If I make it 100%, then it will cause Zenity to stop, even if there are commands left to run. In the example, it would not run the last 'sleep 2' command.

Question

The question parameter allows Zenity to interact with the user by posing a question, or some information, and allowing the user to select from a 'Yes' or 'No' button. The syntax is as follows:

--question Display question dialog
--text=TEXT Set the dialog text
--icon-name=ICON-NAME Set the dialog icon
--no-wrap Do not enable text wrapping
--no-markup Do not enable Pango markup
--default-cancel Give Cancel button focus by default
--ellipsize Enable ellipsizing in the dialog text. This fixes the high window size with long texts
--ok-label Change the 'Yes' label on the button (exit 0)
--cancel-label Change the 'No' label on the button (exit 1)


These we've come across before except for '--default-cancel', '--ok-label' and '--cancel-label'. Before we get into these, let's look at an example with its image in Figure 2:

zenity --question --title "Make a Choice" --text "What do you choose?"
var1=$?
echo $var1


Figure 2.JPG

FIGURE 2

The default button is 'Yes', so if the user just presses the 'ENTER' button on the keyboard, the 'Yes' button is selected. If you specify the '--default-cancel' parameter, then the default button is 'No' and not 'Yes'.

You can change the default buttons from 'Yes' and 'No' to others. The '--ok-label' is the button that is usually 'Yes' and returns an exit code of '0'. The '--cancel-button' is usually the 'No' button that causes and exit code of 1.

In the above example, you can use 'var1' to check for the exit status of the question.

Warning

The warning parameter is a window that allows for you to show a warning message to the user. This, of course, is best in the error handling section of your scripts, but can be used anywhere.

The syntax is as follows:

--warning Display warning dialog
--text=TEXT Set the dialog text
--icon-name=ICON-NAME Set the dialog icon
--no-wrap Do not enable text wrapping
--no-markup Do not enable Pango markup
--ellipsize Enable ellipsizing in the dialog text. This fixes the high window size with long texts


The '--warning' parameter designates the window is a warning. It shows a warning icon, as shown in Figure 3.

Figure 3.JPG

FIGURE 3

The code for the script is:

zenity --warning --text="Warning text that you enter."

The '--text' parameter sets up the text within the window. This text can be as specific as you need and even include variable information. You can change the icon with the parameter '--icon-name'. Examples of changing the icon name are in the first article. The '--no-wrap' parameter allows for the text not to be wrapped it is a long string of text. The '--no-markup' will disable the Pango markup language, which was also covered in the first article. If you do not want a long window when you use long strings of text, use '--ellipsize' to add brackets on the end of the text.

Scale

Shows a window with a slider to allow the user to select a number specified between a '--min-value' and '--max-value'. The initial 'value' can be set in the script.

The command can be set to place the value into a variable to be used in the script later. The usable parameters are:

--scale Display scale dialog
--text=TEXT Set the dialog text
--value=VALUE Set initial value
--min-value=VALUE Set minimum value
--max-value=VALUE Set maximum value
--step=VALUE Set step size
--print-partial Print partial values
--hide-value Hide value


You can set a 'step' value so when the slider is moved, it moves the number by the 'step' value. If the initial value is set to an even number and the step is set to 2, then you can only get an even number from the user. It does seem like the 'step' parameter does not work in the current version of Zenity.

The 'print-partial- parameter stores all the chosen numbers from the user. If the scale is 1-100 and the initial value is 50, the user can switch it to multiple numbers before hitting 'OK'. The values given to the variable will include all the chosen numbers, but the last one in the list is the final selection.

When using the 'hide-value' parameter, the number showing the exact value is not displayed.

Let's look at an example to have a user guess a number between 1 and 100.

#!/bin/bash
number1=$((1 + $RANDOM % 100))
guess1=0
min1=1
max1=100
title1=""
until [[ $guess1 -eq $number1 ]]
do
guess1=`zenity --scale --text="Guess a number between $min1 and $max1" --min-value=$min1 --max-value=$max1 --value=$min1 --title=$title1
if [[ $guess1 -gt $number1 ]];then
title1="Too_High!";
max1=$guess1
elif [[ $guess1 -lt $number1 ]];then
title1="Too_Low!";
min1=$guess1
fi
done
echo "You guessed the number: $number1"


The example shows using Zenity to get a number from the user using a 'scale' to get the user's guess.

Text Info

Sometimes, you may have text you need the user to read. This could be something as simple as a list of instructions or a license agreement.

All the text for the text info window can be placed in a separate file. The file can be loaded and displayed. You can also use HTML code or even a website (it may be best to have an HTML page locally to load). Be aware that when using HTML pages or a URL, if a user clicks on a link, it will be opened in a web browser.

The syntax is as follows:

--text-info Display text information dialog
--filename=FILENAME Open file
--editable Allow changes to text
--font=TEXT Set the text font
--checkbox=TEXT Enable an I read and agree checkbox
--html Enable HTML support
--no-interaction Do not enable user interaction with the WebView. Only works if you use --html option
--url=URL Set an URL instead of a file. Only works if you use --html option
--auto-scroll Auto scroll the text to the end. Only when text is captured from stdin


If you have the text to display in a separate file, use the '--filename' parameter to specify the file. You can make the text editable by the user (--editable). If you wanted, you cen set the font to use (--font). A checkbox can be displayed with text under the text box (--checkbox) so the user can signify that the information was read or agreed to in the text box. If links exist in an HTML or URL, you can specify that no interaction be allowed (--no-interaction). If you have specified HTML, then you can set a URL to show (--url); again, be aware to use '--no-interaction' if any links exist. If the text is brought from 'stdin', then you can have it scroll to the end of the text (--auto-scroll).

Figure 4 shows a Text Info box in Zenity. There is a checkbox for the user to click on to verify that they read the text.

Figure 4.JPG

FIGURE 4

You will need to check the error code to verify that the user selected the checkbox and then clicked 'OK'. The 'OK' box is grayed out until the checkbox is clicked. If the checkbox and 'OK' is clicked, then the error code is '0'. If the user clicks on cancel, then the error code is '1'. A result if '-1' is an error. Sample code is:

zenity --text-info --checkbox="Do you Agree" --filename=textfile
Answer=$?
echo $Answer


The error code is placed into the variable 'Answer'.

Color Selection

If you need to have the user choose a color, then you can use the parameter '--color-selection'.

The parameters to use are:

--color-selection Display color selection dialog
--color=VALUE Set the color
--show-palette Show the palette


The initial color can be set with the '--color' parameter. If you want to see the palette of colors, use the '--show-palette' parameter. An example is shown in Figure 5.

Figure 5.JPG

FIGURE 5

The color values are set as hexadecimal values 00 to FF. The 'FF' value is equivalent to the decimal value of 255. The values are returned from the Zenity box as 'rgb(00,77,FF)' values. The first set of hexadecimal values represent red, the second is green and the last is blue.

If we were to click on the '+' at the bottom to create a custom color, we would get a window similar to Figure 6. The window may vary depending on system distro and version.

Figure 6.JPG

FIGURE 6

Password


There are times you may want a user to type in a password or some information that should not be displayed on the screen. In a password box, the text is replaced with dots, as shown in Figure 7.

Figure 7.JPG

FIGURE 7

You can also ask for the user name as well with the parameter '--username'. The syntax is:

--password Display password dialog
--username Display the username option


The output is in a non-encrypted format in a variable. Be aware that any value returned from the command is readable. If you return bot the username and password, they are separated by a pipe '|'.

Forms

A form allows you to combine multiple types of boxes into one box.

--forms Display forms dialog
--add-entry=Field name Add a new Entry in forms dialog
--add-password=Field name Add a new Password Entry in forms dialog
--add-calendar=Calendar field name Add a new Calendar in forms dialog
--add-list=List field and header name Add a new List in forms dialog
--list-values=List of values separated by | List of values for List
--column-values=List of values separated by | List of values for columns
--add-combo=Combo box field name Add a new combo box in forms dialog
--combo-values=List of values separated by | List of values for combo box
--show-header Show the columns header
--text=TEXT Set the dialog text
--separator=SEPARATOR Set output separator character
--forms-date-format=PATTERN Set the format for the returned date


The box returned can have numerous other boxes mixed in and allow you to get a whole collection of data at once on one screen.

An example is shown in Figure 8.

Figure 8.JPG

FIGURE 8

The code for generating Figure 8 is:

var1=$(zenity --forms --title="Create user" --text="Add new user" --separator "-"\
--add-entry="First Name" \
--add-entry="Last Name" \
--add-entry="Username" \
--add-password="Password" \
--add-password="Confirm Password" \
--add-calendar="Birthdate")
IFS=- read fname lname uname pass cpass bdate <<< $var1
echo $fname
echo $lname
echo $uname
echo $pass
echo $cpass
echo $bdate


The separator is set to a dash so the 'IFS' command can use it to cut out the individual variables from 'var1'. Here, you can then check that the password and confirm password are the same and to also check any other issues with the values of the variables.

I won't go over this one, since these are all commands used before.

You can add as many fields as you want to make up the form. Just be aware of the screen size so you do not overfill the screen and have parts go off of the viewable area.

Conclusion

Zenity is a very useful GUI tool for scripts. It can make your scripts look more professional and more interactive.

When you are creating your next script, give Zenity a try.
 
Last edited by a moderator:

Members online


Top