Ricerca nel sito web

Crea le tue applicazioni "Browser Web" e "Registratore desktop" utilizzando PyGobject - Parte 3


Questa è la terza parte della serie sulla creazione di applicazioni GUI sul desktop Linux utilizzando PyGObject. Oggi parleremo dell'utilizzo di alcuni moduli e librerie Python avanzati nei nostri programmi come 'os', 'WebKit', 'requests' e altri, oltre ad alcune altre informazioni utili per la programmazione.

Requisiti

È necessario seguire tutte le parti precedenti della serie da qui, per continuare con ulteriori istruzioni sulla creazione di applicazioni più avanzate:

  1. Creare applicazioni GUI sul desktop Linux utilizzando PyGObject - Parte 1
  2. Creazione di applicazioni PyGobject avanzate su Linux – Parte 2

I moduli e le librerie in Python sono molto utili, invece di scrivere molti sottoprogrammi per svolgere lavori complicati che richiederanno molto tempo e lavoro, puoi semplicemente importarli! Sì, basta importare i moduli e le librerie di cui hai bisogno nel tuo programma e potrai risparmiare molto tempo e fatica per completare il tuo programma.

Esistono molti moduli famosi per Python, che puoi trovare su Python Module Index.

Puoi anche importare librerie per il tuo programma Python, da “gi.repository import Gtk” questa riga importa la libreria GTK nel programma Python, ci sono molte altre librerie come Gdk, WebKit.. ecc.

Creazione di applicazioni GUI avanzate

Oggi creeremo 2 programmi:

  1. Un semplice browser web; che utilizzerà la libreria WebKit.
  2. Un registratore desktop che utilizza il comando "avconv"; che utilizzerà il modulo "os" di Python.

D'ora in poi non ti spiegherò come trascinare e rilasciare i widget nel designer Glade, ti dirò solo il nome dei widget che devi creare, inoltre ti darò il .glade per ciascun programma e sicuramente il file Python.

Creazione di un semplice browser Web

Per creare un browser web, dovremo utilizzare il motore “WebKit ”, che è un motore di rendering open source per il web, è lo stesso utilizzato in Chrome/Chromium, per maggiori informazioni a riguardo puoi fare riferimento al sito ufficiale Webkit.org.

Per prima cosa dovremo creare la GUI, aprire il designer Glade e aggiungere i seguenti widget. Per ulteriori informazioni su come creare widget, segui la Parte 1 e la Parte 2 di questa serie (link forniti sopra).

  1. Crea il widget "finestra1".
  2. Crea i widget "box1" e "box2".
  3. Crea widget "pulsante1" e "pulsante2".
  4. Crea il widget "voce 1".
  5. Crea il widget "scrolledwindow1".

Dopo aver creato i widget, otterrai la seguente interfaccia.

Non c'è niente di nuovo, tranne il widget "Finestra scorrevole"; questo widget è importante per permettere di impiantare al suo interno il motore WebKit, utilizzando il widget “Finestra Scorrita ” potrai anche scorrere orizzontalmente e verticalmente mentre navigare nei siti web.

Dovrai ora aggiungere il gestore "backbutton_clicked " al segnale "backbutton_clicked" del pulsante Indietro, "refreshbutton_clicked" gestore al pulsante Aggiorna “segnale cliccato” e “enterkey_clicked” gestore al segnale “attivato” per la voce.

Il file .glade completo per l'interfaccia è qui.

<?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>

Ora copia il codice sopra e incollalo nel file “ui.glade” nella tua cartella Home. Ora crea un nuovo file chiamato “mywebbrowser.py ” e inserisci al suo interno il seguente codice, tutta la spiegazione è nei commenti.

#!/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()

Salvare il file ed eseguirlo.

chmod 755 mywebbrowser.py
./mywebbrowser.py

E questo è ciò che otterrai.

Puoi fare riferimento alla documentazione ufficiale WebKitGtk per scoprire più opzioni.

Creazione di un semplice registratore desktop

In questa sezione impareremo come eseguire comandi di sistema locali o script di shell dal file Python utilizzando il modulo 'os', che ci aiuterà a creare un semplice registratore dello schermo per il desktop utilizzando il comando 'avconv'.

Apri il designer Glade e crea i seguenti widget:

  1. Crea il widget "finestra1".
  2. Crea il widget "box1".
  3. Crea widget "pulsante1", "pulsante2" e "pulsante3".
  4. Crea il widget "voce 1".

Dopo aver creato i suddetti widget, otterrai l'interfaccia sottostante.

Ecco il file 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>

Come al solito, copia il codice sopra e incollalo nel file “ui.glade” nella tua directory home, crea un nuovo file “myrecorder.py” e inserisci quanto segue codice al suo interno (ogni nuova riga è spiegata nei commenti).

#!/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()

Ora esegui il file applicando i seguenti comandi nel terminale.

chmod 755 myrecorder.py
./myrecorder.py

E hai il tuo primo registratore da tavolo.

Puoi trovare ulteriori informazioni sul modulo "os" nella libreria del sistema operativo Python.

E questo è tutto, creare applicazioni per il desktop Linux non è difficile utilizzando PyGObject, devi solo creare la GUI, importare alcuni moduli e collegare il file Python con la GUI, niente di più, niente di meno. Ci sono molti tutorial utili su come eseguire questa operazione nel sito Web PyGObject:

Hai provato a creare applicazioni utilizzando PyGObject? Cosa ne pensi di farlo? Quali applicazioni hai sviluppato in precedenza?