Zenity linux что это

Zenity linux что это

For example, zenity —question will return either 0 or 1, depending on whether the user pressed OK or Cancel . zenity —entry will output on standard output what the user typed into the text entry field.

Comprehensive documentation is available in the GNOME Help Browser, under GNOME/Utilities .

OPTIONS

—calendar Display calendar dialog —entry Display text entry dialog —error Display error dialog —file-selection Display file selection dialog —info Display info dialog —list Display list dialog —notification Display notification icon —progress Display progress indication dialog —question Display question dialog —text-info Display text information dialog —warning Display warning dialog —scale Display scale dialog

—title=TITLE Set the dialog title —window-icon=ICONPATH Set the window icon —width=WIDTH Set the dialog width —height=HEIGHT Set the dialog height

—text=STRING Set the dialog text —day=INT Set the calendar day —month=INT Set the calendar month —year=INT Set the calendar year —date-format=PATTERN Set the format for the returned date

Text entry options

—text=STRING Set the dialog text —entry-text=STRING Set the entry text —hide-text Hide the entry text

Error options —text=STRING Set the dialog text —no-wrap Do not enable text wrapping

File selection options —filename=FILENAME Set the filename —multiple Allow selection of multiple filenames in file selection dialog —directory Activate directory-only selection —save Activate save mode —separator=SEPARATOR Specify separator character when returning multiple filenames —confirm-overwrite Confirm file selection if filename already exists

Info options —text=STRING Set the dialog text —no-wrap Do not enable text wrapping

—text=STRING Set the dialog text —column=STRING Set the column header —checklist Use check boxes for first column —radiolist Use radio buttons for first column —separator=STRING Set output separator character —multiple Allow multiple rows to be selected —editable Allow changes to text —print-column=STRING Specify what column to print to standard output. The default is to return the first column. ‘ALL’ may be used to print all columns. —hide-column=NUMBER Hide a specific column

—text=STRING Set the notification text —listen Listen for commands on stdin

—text=STRING Set the dialog text —percentage=INT Set initial percentage —auto-close Close dialog when 100% has been reached —auto-kill Kill parent process if cancel button is pressed —pulsate Pulsate progress bar

—text=STRING Set the dialog text —no-wrap Do not enable text wrapping

—filename=FILENAME Open file —editable Allow changes to text

—text=STRING Set the dialog text —no-wrap Do not enable text wrapping

—text=STRING 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

-?, —help Show summary of options. —about Display an about dialog. —version Show version of program.

Also the standard GTK+ options are accepted.

EXAMPLES

Display a file selector with the title Select a file to remove . The file selected is returned on standard output. zenity —title=»Select a file to remove» —file-selection

Display a text entry dialog with the title Select Host and the text Select the host you would like to flood-ping . The entered text is returned on standard output. zenity —title «Select Host» —entry —text «Select the host you would like to flood-ping»

Читайте также:  Системная ошибка при переустановке windows

Display a dialog, asking Microsoft Windows has been found! Would you like to remove it? . The return code will be 0 (true in shell) if OK is selected, and 1 (false) if Cancel is selected. zenity —question —title «Alert» —text «Microsoft Windows has been found! Would you like to remove it?»

Show the search results in a list dialog with the title Search Results and the text Finding all header files. . find . -name ‘*.h’ | zenity —list —title «Search Results» —text «Finding all header files..» —column «Files»

Show an icon in the notification area zenity —notification —window-icon=update.png —text «System update necessary!»

Display a weekly shopping list in a check list dialog with Apples and Oranges pre selected zenity —list —checklist —column «Buy» —column «Item» TRUE Apples TRUE Oranges FALSE Pears FALSE Toothpaste

Display a progress dialog while searching for all the postscript files in your home directory find $HOME -name ‘*.ps’ | zenity —progress —pulsate

Источник

Zenity – Creates Graphical (GTK+) Dialog Boxes in Command-line and Shell Scripts

GNU Linux, the operating system built on very powerful Kernel called Linux. Linux is famous for its command Line operations. With the invent of Linux in day-to-day and Desktop computing, nix remains no more biased towards command-Line, it is equally Graphical and developing Graphical application remains no more a difficult task.

Zenity Display Graphical Boxes

Here in this article we will be discussing creation and execution of simple Graphical Dialog box using GTK+ application called “Zenity“.

What is Zenity?

Zenity is an open source and a cross-platform application which displays GTK+ Dialog Boxes in command-line and using shell scripts. It allows to ask and present information to/from shell in Graphical Boxes. The application lets you create Graphical dialog boxes in command-line and makes the interaction between user and shell very easy.

There are other alternatives, but nothing compares to the simplicity of Zenity, specially when you don’t need complex programming. Zenity, a tool you must have your hands on.

Zenity Features

  1. FOSS Software
  2. Cross Platform Application
  3. Allow GTK+ Dialog Box Execution
  4. Command Line Tool
  5. Support in Shell Scripting

Usefulness

  1. Easy GUI Creation
  2. Less features than other complex Tools
  3. Enables shell scripts to interact with a GUI users
  4. Simple dialog creation is possible for graphical user interaction

Since Zenity is available for all known major platforms, and based on GTK+ library, Zenity program can be ported to/from another platform.

Installation of Zenity in Linux

Zentity is by default installed or available in repository of most of the Standard Linux distribution of today. You can check if is installed onto your machine or not by executing following commands.

If it’s not installed, you can install it using Apt or Yum command as shown below.

Moreover you can also build it from the source files, download the latest Zenity source package (i.e. current version 3.8) using a following link.

Zenity Basic Dialog Boxes

Some of the basic Dialogs of Zenity, which can be invoked directly from the command-line.

1. How about a quick calendar dialog?
2. An error Dialog Box
3. A General text Entry Dialog Box
4. An Information Dialog
5. A question Dialog box
6. A progress Bar
7. Scale Dialog
8. A Password Dialog
9. A Form Dialog box
10. An about Dialog

Create Shell Script Dialog

Now we would be discussing Zenity Dialog creation using simple shell scripts here. Although we can create single Dialog by executing Zenity commands directly from the shell (as we did above) but then we can’t link two Dialog boxes in order to obtain some meaningful result.

Читайте также:  Как запустить winrar от имени администратора windows 10

How about an interactive dialog box which takes input from you, and shows the result.

Save it to ‘anything.sh‘ (conventionally) and do not forget to make it executable. Set 755 permission on anything.sh file and run the script.

Enter Your First Name Welcome Dialog Enter Your Last Name Welcome Message

About Script Description

The conventional shebang aka hashbang

In the below line ‘first’ is a variable and the value of variable is Generated at run time.

    1. –entry‘ means zenity is asked to generate an text Entry box.
    2. – title=‘ defines the title of generated text box.
    3. —text=‘ defines the text that is available on text Entry box.

This line of the below script file is for generation of Information (–info) Dialog box, with title “Welcome” and Text “Mr./Ms.first”

This Line of the script is Similar to line number two of the script except here a new variable ‘last’ is defined.

This last line of the script is again similar to the third line of the script and it generates information Dialog box which contains both the variables ‘$first’ and ‘$last’.

For more information on how to create custom dialog boxes using shell script, visit at following reference page Zenity.

In the next article we would be integrating Zenity with more shell script for GUI user interaction. Till then stay tuned and connected to Tecmint. Don’t forget to give your valuable feedback in comment section.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Zenity linux что это

Взаимодействие shell-скриптов с пользователем посредством Zenity

В данной статье речь пойдёт о том, каким образом можно без особых усилий
сделать графический интерфейс к shell-скриптам.

Если вы хотите сделать взаимодействие ваших программ с пользователем более простым, то эта статья для вас, и не важно, какой язык вы используете, будь то bash, perl, python и т. п.

Итак, Zenity является утилитой отображения диалогов. Программа имеется в составе большинства распостранённых дистрибутивов Linux, хотя ее можно скомпилировать или найти уже в бинарном виде практически для любой *nix-системы.

Взаимодействие с X-сервером производится с помощью библиотеки GTK+.

Рассмотрим функциональные возможности данной программы. Имеется десять видов диалогов.

1. Calendar — календарь (date-picker).

2. Entry — однострочное текстовое поле ввода.

3. Text-info — диалог отображения многострочной текстовой информации, который может применяться и как поле ввода. Хотя, по всей видимости, это не является его основным назначением.

4. Error — сообщение об ошибке.

5. Info — сообщение общего характера.

6. Warning — предупреждение.

7. Question — вопросительное сообщение с возможностью ввода утвердительного или отрицательного ответа.

8. File-selection — выбор файла.

Читайте также:  Монитор windows 10 lenovo

9. List — список с возможностью выбора и редактирования его элементов.

10. Progress — Progress bar dialog. Отображает статус выполнения текущей операции.

Заставить утилиту делать то, что мы пожелаем, можно посредством запуска программы с соответствующими параметрами. Имя любого из параметров состоит более чем из одного символа и, следовательно, имеет префикс «—» — «два минуса». При завершении выполнения будут выведены результирующие данные в stdout или же код будет просто возвращён в stderr. Например, чтобы отобразить сообщение об ошибке, достаточно выполнить следующее:

В результате мы увидим сообщение об ошибке.

Все диалоги имеют некоторые свойства, значения которых также определяются параметрами запуска. Общие для всех диалогов свойства, то есть те, которыми обладают все диалоги, такие: title, window-icon, width, height. Очевидно, что title определяет заголовок окна, window-icon — пиктограмму, а width
и height — ширину и высоту окна соответственно.

Теперь можно поговорить о каждом из диалогов подробнее.

Info, question, warning и error

Text — выводимое сообщение. Различаются данные диалоги лишь пиктограммой, находящейся напротив сообщения. Question имеет две кнопки, соответствующие положительному и отрицательному ответу на сообщение.

* Text — сообщение, выводимое над полем выбора даты.

* Day, month и year — день, месяц и год, которые будут установлены по умолчанию.

* Date-format — строка, определяющая формат возвращаемой даты. Формат строки эквивалентен формату вызова функции strftime.

Попробуем написать простое приложение, запрашивающее дату рождения пользователя.

* Text — сообщение, выводимое над полем ввода.

* Entry-text — текст, которым автоматически заполняется поле ввода.

* Hide-text — если присутствует, то вводимые символы отображаются «звёздочками».

В качестве примера попробуем написать простое приложение, осуществляющее запуск вводимой команды.

* Column — заголовок столбца.

* Check-list — использование check box для первого столбца.

* Radio-list — использование radio buttons для первого столбца.

* Separator — разделитель, использующийся при выводе информации. По умолчанию это символ «|».

* Editable — присутствие данного параметра означает, что пользователь может редактировать элементы списка.

* File-name — имя файла, содержимое которого будет отображено.

* Editable — использование данного параметра аналогично List.

* File-name — имя файла, устанавливаемое по умолчанию.

* Multiple — возможность выбора сразу нескольких файлов.

* Separator — использование данного параметра аналогично List.

* Text — сообщение над progress bar.

* Percentage — начальное состояние, указываемое в процентах.

* Auto-close — автоматическое закрытие диалога после достижения 100%.

* Pulsate — определяет отображение «пульсирующего» прогресса.

Кроме того, Zenity имеет ещё несколько менее важных дополнительных опций.

* —gdk-debug=FLAGS — установка флагов отладки Gdk;

* —gdk-no-debug=FLAGS — отмена флагов отладки Gdk;

* —sync — использование синхронных X-вызовов;

* —name=NAME — имя программы, используемое оконным менеджером;

* —class=CLASS — класс программы, используемый оконным менеджером;

* —gtk-debug=FLAGS — установка флагов отладки Gtk+;

* —gtk-no-debug=FLAGS — отмена флагов отладки Gtk+;

* —g-fatal-warnings — все предупреждения приводят к завершению выполнения;

* —gtk-module=MODULE — загрузить дополнительный модуль Gtk.

Кроме Zenity, есть ещё такие средства, как xdialog , dialog , kdialog , xmessage . Рассмотрим вкратце некоторые из них.

Dialog — программа, использующая Ncurses для вывода диалогов. Вследствие этого является достаточно универсальной, так как не все и не всегда пользуются X-Window.

Вот список параметров dialog:

Kdialog поставляется в составе KDE. Имеет сходный интерфейс с dialog и xdialog. Но, на мой взгляд, kdialog более избыточен и менее функционален, нежели Zenity. Xmessage предназначается исключительно для вывода сообщений, но внешний вид, думаю, редкого пользователя может порадовать.

Необходимо учесть, что пользователь может и не иметь установленной Zenity. И не стоит забывать о том, что есть средства, такие как xdialog, dialog, kdialog, kmessage, и другие. Может быть, в вашем случае они подойдут больше.

Источник

Оцените статью