Pesquisa de site

Crie seus próprios aplicativos de 'navegador da Web' e 'gravador de desktop' usando PyGobject - Parte 3


Esta é a terceira parte da série sobre como criar aplicativos GUI no desktop Linux usando PyGObject. Hoje falaremos sobre o uso de alguns módulos e bibliotecas Python avançados em nossos programas como 'os', 'WebKit', 'requests' e outros, além de algumas outras informações úteis para programação.

Requisitos

Você deve passar por todas as partes anteriores da série a partir daqui, para continuar com mais instruções sobre como criar aplicativos mais avançados:

  1. Crie aplicativos GUI no desktop Linux usando PyGObject – Parte 1
  2. Criando aplicativos PyGobject avançados no Linux – Parte 2

Módulos e bibliotecas em Python são muito úteis, em vez de escrever muitos subprogramas para fazer alguns trabalhos complicados que exigirão muito tempo e trabalho, você pode simplesmente importá-los! Sim, basta importar os módulos e bibliotecas necessários para o seu programa e você poderá economizar muito tempo e esforço para concluir o seu programa.

Existem muitos módulos famosos para Python, que você pode encontrar no Python Module Index.

Você também pode importar bibliotecas para o seu programa Python, de “gi.repository import Gtk” esta linha importa a biblioteca GTK para o programa Python, existem muitas outras bibliotecas como Gdk, WebKit.. etc.

Criando aplicativos GUI avançados

Hoje, criaremos 2 programas:

  1. Um navegador simples; que usará a biblioteca WebKit.
  2. Um gravador de desktop usando o comando ‘avconv’; que usará o módulo ‘os’ do Python.

Não vou explicar como arrastar e soltar widgets no designer Glade de agora em diante, apenas direi o nome dos widgets que você precisa criar, além disso darei a você o .glade para cada programa e o arquivo Python com certeza.

Criando um navegador simples

Para criar um navegador web, teremos que usar o motor “WebKit”, que é um mecanismo de renderização de código aberto para a web, é o mesmo usado em Chrome/Chromium, para mais informações sobre ele você pode consultar o site oficial Webkit.org.

Primeiro, teremos que criar a GUI, abrir o designer Glade e adicionar os seguintes widgets. Para obter mais informações sobre como criar widgets, siga a Parte 1 e a Parte 2 desta série (links fornecidos acima).

  1. Crie o widget ‘janela1’.
  2. Crie widgets ‘box1’ e ‘box2’.
  3. Crie o widget ‘button1’ e ‘button2’.
  4. Crie o widget ‘entrada1’.
  5. Crie o widget ‘scrolledwindow1’.

Depois de criar widgets, você obterá a seguinte interface.

Não há nada de novo, exceto o widget “Janela rolada”; este widget é importante para permitir que o motor WebKit seja implantado dentro dele, usando o widget “Janela Rolada” você também poderá rolar horizontalmente e verticalmente enquanto você navegar nos sites.

Agora você terá que adicionar o manipulador “backbutton_clicked” ao sinal do botão Voltarclicado”, “refreshbutton_clicked” manipulador para o botão Atualizar “sinal clicado” e manipulador “enterkey_clicked” para o sinal “ativado” para a entrada.

O arquivo .glade completo da interface está aqui.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.16.1 -->
<interface>
  <requires lib="gtk+" version="3.10"/>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="title" translatable="yes">Our Simple Browser</property>
    <property name="window_position">center</property>
    <property name="default_width">1000</property>
    <property name="default_height">600</property>
    <property name="icon_name">applications-internet</property>
    <child>
      <object class="GtkBox" id="box1">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <child>
          <object class="GtkBox" id="box2">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-go-back</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="relief">half</property>
                <property name="use_stock">True</property>
                <property name="always_show_image">True</property>
                <signal name="clicked" handler="backbutton_clicked" swapped="no"/>
              </object>
              <packing>
                <property name="expand">False</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-refresh</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="relief">half</property>
                <property name="use_stock">True</property>
                <property name="always_show_image">True</property>
                <signal name="clicked" handler="refreshbutton_clicked" swapped="no"/>
              </object>
              <packing>
                <property name="expand">False</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
            <child>
              <object class="GtkEntry" id="entry1">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <signal name="activate" handler="enterkey_clicked" swapped="no"/>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">2</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkScrolledWindow" id="scrolledwindow1">
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="hscrollbar_policy">always</property>
            <property name="shadow_type">in</property>
            <child>
              <placeholder/>
            </child>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

Agora copie o código acima e cole-o no arquivo “ui.glade” em sua pasta pessoal. Agora crie um novo arquivo chamado “mywebbrowser.py” e insira o seguinte código dentro dele, toda a explicação está nos comentários.

#!/usr/bin/python 
-*- coding: utf-8 -*- 

## Here we imported both Gtk library and the WebKit engine. 
from gi.repository import Gtk, WebKit 

class Handler: 
  
  def backbutton_clicked(self, button): 
  ## When the user clicks on the Back button, the '.go_back()' method is activated, which will send the user to the previous page automatically, this method is part from the WebKit engine. 
    browserholder.go_back() 

  def refreshbutton_clicked(self, button): 
  ## Same thing here, the '.reload()' method is activated when the 'Refresh' button is clicked. 
    browserholder.reload() 
    
  def enterkey_clicked(self, button): 
  ## To load the URL automatically when the "Enter" key is hit from the keyboard while focusing on the entry box, we have to use the '.load_uri()' method and grab the URL from the entry box. 
    browserholder.load_uri(urlentry.get_text()) 
    
## Nothing new here.. We just imported the 'ui.glade' file. 
builder = Gtk.Builder() 
builder.add_from_file("ui.glade") 
builder.connect_signals(Handler()) 

window = builder.get_object("window1") 

## Here's the new part.. We created a global object called 'browserholder' which will contain the WebKit rendering engine, and we set it to 'WebKit.WebView()' which is the default thing to do if you want to add a WebKit engine to your program. 
browserholder = WebKit.WebView() 

## To disallow editing the webpage. 
browserholder.set_editable(False) 

## The default URL to be loaded, we used the 'load_uri()' method. 
browserholder.load_uri("https://linux-console.net") 

urlentry = builder.get_object("entry1") 
urlentry.set_text("https://linux-console.net") 

## Here we imported the scrolledwindow1 object from the ui.glade file. 
scrolled_window = builder.get_object("scrolledwindow1") 

## We used the '.add()' method to add the 'browserholder' object to the scrolled window, which contains our WebKit browser. 
scrolled_window.add(browserholder) 

## And finally, we showed the 'browserholder' object using the '.show()' method. 
browserholder.show() 
 
## Give that developer a cookie ! 
window.connect("delete-event", Gtk.main_quit) 
window.show_all() 
Gtk.main()

Salve o arquivo e execute-o.

chmod 755 mywebbrowser.py
./mywebbrowser.py

E é isso que você obterá.

Você pode consultar a documentação oficial do WebKitGtk para descobrir mais opções.

Criando um gravador de desktop simples

Nesta seção, aprenderemos como executar comandos do sistema local ou scripts de shell a partir do arquivo Python usando o módulo 'os', que nos ajudará a criar um gravador de tela simples para a área de trabalho usando o Comando 'avconv'.

Abra o designer Glade e crie os seguintes widgets:

  1. Crie o widget ‘janela1’.
  2. Crie o widget ‘box1’.
  3. Crie widgets ‘button1’, ‘button2’ e ‘button3’.
  4. Crie o widget ‘entrada1’.

Depois de criar os widgets acima, você obterá a interface abaixo.

Aqui está o arquivo ui.glade completo.

<?xml version="1.0" encoding="UTF-8"?> 
<!-- Generated with glade 3.16.1 --> 
<interface> 
  <requires lib="gtk+" version="3.10"/> 
  <object class="GtkWindow" id="window1"> 
    <property name="can_focus">False</property> 
    <property name="title" translatable="yes">Our Simple Recorder</property> 
    <property name="window_position">center</property> 
    <property name="default_width">300</property> 
    <property name="default_height">30</property> 
    <property name="icon_name">applications-multimedia</property> 
    <child> 
      <object class="GtkBox" id="box1"> 
        <property name="visible">True</property> 
        <property name="can_focus">False</property> 
        <child> 
          <object class="GtkEntry" id="entry1"> 
            <property name="visible">True</property> 
            <property name="can_focus">True</property> 
          </object> 
          <packing> 
            <property name="expand">False</property> 
            <property name="fill">True</property> 
            <property name="position">0</property> 
          </packing> 
        </child> 
        <child> 
          <object class="GtkButton" id="button1"> 
            <property name="label">gtk-media-record</property> 
            <property name="visible">True</property> 
            <property name="can_focus">True</property> 
            <property name="receives_default">True</property> 
            <property name="use_stock">True</property> 
            <property name="always_show_image">True</property> 
            <signal name="clicked" handler="recordbutton" swapped="no"/> 
          </object> 
          <packing> 
            <property name="expand">True</property> 
            <property name="fill">True</property> 
            <property name="position">1</property> 
          </packing> 
        </child> 
        <child> 
          <object class="GtkButton" id="button2"> 
            <property name="label">gtk-media-stop</property> 
            <property name="visible">True</property> 
            <property name="can_focus">True</property> 
            <property name="receives_default">True</property> 
            <property name="use_stock">True</property> 
            <property name="always_show_image">True</property> 
            <signal name="clicked" handler="stopbutton" swapped="no"/> 
          </object> 
          <packing> 
            <property name="expand">True</property> 
            <property name="fill">True</property> 
            <property name="position">2</property> 
          </packing> 
        </child> 
        <child> 
          <object class="GtkButton" id="button3"> 
            <property name="label">gtk-media-play</property> 
            <property name="visible">True</property> 
            <property name="can_focus">True</property> 
            <property name="receives_default">True</property> 
            <property name="use_stock">True</property> 
            <property name="always_show_image">True</property> 
            <signal name="clicked" handler="playbutton" swapped="no"/> 
          </object> 
          <packing> 
            <property name="expand">True</property> 
            <property name="fill">True</property> 
            <property name="position">3</property> 
          </packing> 
        </child> 
      </object> 
    </child> 
  </object> 
</interface>

Como de costume, copie o código acima e cole-o no arquivo “ui.glade” em seu diretório inicial, crie um novo arquivo “myrecorder.py” e digite o seguinte código dentro dele (cada nova linha é explicada nos comentários).

#!/usr/bin/python 
-*- coding: utf-8 -*- 

## Here we imported both Gtk library and the os module. 
from gi.repository import Gtk 
import os 
        
class Handler: 
  def recordbutton(self, button): 
    ## We defined a variable: 'filepathandname', we assigned the bash local variable '$HOME' to it + "/" + the file name from the text entry box. 
    filepathandname = os.environ["HOME"] + "/" + entry.get_text() 
    
    ## Here exported the 'filepathandname' variable from Python to the 'filename' variable in the shell. 
    os.environ["filename"] = filepathandname 
    
    ## Using 'os.system(COMMAND)' we can execute any shell command or shell script, here we executed the 'avconv' command to record the desktop video & audio. 
    os.system("avconv -f x11grab -r 25 -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -i :0.0 -vcodec libx264 -threads 4 $filename -y & ") 
    
    
  def stopbutton(self, button): 
    ## Run the 'killall avconv' command when the stop button is clicked. 
    os.system("killall avconv") 
    
  def playbutton(self, button): 
  ## Run the 'avplay' command in the shell to play the recorded file when the play button is clicked. 
    os.system("avplay $filename &") 
    
    
## Nothing new here.. We just imported the 'ui.glade' file. 
builder = Gtk.Builder() 
builder.add_from_file("ui.glade") 
builder.connect_signals(Handler()) 

window = builder.get_object("window1") 
entry = builder.get_object("entry1") 
entry.set_text("myrecording-file.avi") 

## Give that developer a cookie ! 
window.connect("delete-event", Gtk.main_quit) 
window.show_all() 
Gtk.main()

Agora execute o arquivo aplicando os seguintes comandos no terminal.

chmod 755 myrecorder.py
./myrecorder.py

E você ganhou seu primeiro gravador de desktop.

Você pode encontrar mais informações sobre o módulo ‘os’ na Python OS Library.

E é isso, criar aplicações para o desktop Linux não é difícil usando PyGObject, basta criar a GUI, importar alguns módulos e vincular o arquivo Python à GUI, nada mais, nada menos. Existem muitos tutoriais úteis sobre como fazer isso no site PyGObject:

Você já tentou criar aplicativos usando PyGObject? O que você acha de fazer isso? Quais aplicativos você desenvolveu antes?