Zenity - Criando caixas de diálogos no shell script com zenity


{getToc} $title={Índice}

Introdução

Zenity é um software open source da gnome que possibilita a exibição de caixas de diálogo executadas por linha de comando.

Para o exemplo, foi utilizado um script bash, porem outras linguagens de script, como Perl e Python, podem ser usadas para construir aplicativos GUI.

Primeiros passos

O zenity é nativo em distros Linux com interface gnome, para verificar as opções disponíveis utilize o comando:

```terminal
zenity --help
```

Saída obtida:

```terminal
<pre><font color="#4E9A06"><b>brunolima@OptiPlex-7020</b></font>:<font color="#3465A4"><b>~/teste</b></font>$ zenity --help
Usage:
  zenity [OPTION…]

Help Options:
  -h, --help                                        Show help options
  --help-all                                        Show all help options
  --help-general                                    Show general options
  --help-calendar                                   Show calendar options
  --help-entry                                      Show text entry options
  --help-error                                      Show error options
  --help-info                                       Show info options
  --help-file-selection                             Show file selection options
  --help-list                                       Show list options
  --help-notification                               Show notification icon options
  --help-progress                                   Show progress options
  --help-question                                   Show question options
  --help-warning                                    Show warning options
  --help-scale                                      Show scale options
  --help-text-info                                  Show text information options
  --help-color-selection                            Show color selection options
  --help-password                                   Show password dialog options
  --help-forms                                      Show forms dialog options
  --help-misc                                       Show miscellaneous options
  --help-gtk                                        Show GTK+ Options

Application Options:
  --calendar                                        Display calendar dialog
  --entry                                           Display text entry dialog
  --error                                           Display error dialog
  --info                                            Display info dialog
  --file-selection                                  Display file selection dialog
  --list                                            Display list dialog
  --notification                                    Display notification
  --progress                                        Display progress indication dialog
  --question                                        Display question dialog
  --warning                                         Display warning dialog
  --scale                                           Display scale dialog
  --text-info                                       Display text information dialog
  --color-selection                                 Display color selection dialog
  --password                                        Display password dialog
  --forms                                           Display forms dialog
  --display=DISPLAY                                 X display to use

</pre>
```

Note que temos um help para cada opção, caso utilize um comando especifico, verifique o seu submenu --help-comando.

Caixas de informações

Para as caixas de informações iremos utilizar as opções para o exemplo:

  • notification
  • error
  • warning
  • text-info  

No exemplo iremos tratar essas caixas como output, por tanto não analisaremos seu retorno.

Exemplo shell script:

```bash
#!/bin/bash

zenity --notification  --window-icon="info" --text="teste iniciado"
sleep 1.0

zenity --warning --text="Teste em andamento"
sleep 1.0

zenity --error --text="Teste apresentou erro."
sleep 1.0

echo "acesse microprogramador.com.br" > teste.txt
zenity --text-info --filename teste.txt
```

Após criar o script iremos dar permissão de execução

```bash
chmod +x teste.sh
```

Saída obtida:


Entrada de dados

Para as caixas de entrada iremos utilizar as opções para o exemplo:

  • question
  • entry
  • list
Exemplo 1 shell script:

```bash
#!/bin/bash

if zenity --question --text="Deseja iniciar?"; then
# caso o retorno de question seja true, receba o nome
nome=$(zenity --entry --text "nome")
echo $nome
else
# caso o retorno de question seja false
zenity --warning --text="Saindo do script :("
fi
```

Saída obtida:


Exemplo 2 shell script:

```bash
#!/bin/bash

numero=$(zenity --list \
--title="Numero" \
--text='selecione um numero' \
--width=300 \
--height=450 \
--radiolist \
--column="" \
--column="" \
2 2 \
3 3 \
4 4 \
5 5 \
6 6 \
7 7 \
8 8 \
9 9 \
10 10 )

zenity --warning --text="Numero selecionado $numero"
```

Saída obtida:


Editando as caixas

É possível editar o tamanho das caixas e textos, consulte help.gnome para mais informações.

No exemplo iremos alterar o tamanho das caixas e mudar a cor do conteúdo para negrito:

```bash
#!/bin/bash

numero=$(zenity --list \
--title="Numbero" \
--text='<big><b>selecione um numero</b></big>' \
--width=300 \
--height=450 \
--radiolist \
--column="" \
--column="" \
2 2 \
3 3 \
4 4 \
5 5 \
6 6 \
7 7 \
8 8 \
9 9 \
10 10 )

zenity --warning --text="Numero selecionado <b>$numero</b>" --width=300 --height=300
```

Saída obtida:


Barra de progresso

O exemplo a seguir mostra o funcionamento da barra de progresso:

```bash
#!/bin/bash

(
    echo "# inicio do teste"
    echo "10" ; sleep 1

    echo "# testando ..."
    echo "25" ; sleep 1
    echo "75" ; sleep 1

    echo "# teste finalizado"
    echo "100" ; sleep 1

) |
zenity --progress \
  --title="Testing the Network" \
  --width=400 \
  --height=100 \
  --percentage=0 
```

Saída obtida:


Consulte o menu --help para identificar todas as opções presentes.

Bruno Lima

Engenheiro de computação atuando em desenvolvimento de sistemas embarcados (Firmware) com microcontroladores e processadores (Linux Embarcado). Contribuidor de projetos públicos e fóruns de c/c++. linkedin github

Postar um comentário

Deixe seu comentário ou sua sugestão!

Postagem Anterior Próxima Postagem

Formulário de contato