Luo oma verkkoselaimesi ja työpöytätallenninsovelluksesi käyttämällä PyGobjectia - osa 3


Tämä on kolmas sarja GUI-sovellusten luomisesta Linux-työpöydälle PyGObjectia käyttäen. Tänään puhumme joidenkin kehittyneiden Python-moduulien ja kirjastojen käytöstä ohjelmissamme, kuten ' os ', ' WebKit ', ' pyynnöt ja toiset, muiden hyödyllisten ohjelmointitietojen lisäksi.

Sinun täytyy käydä läpi kaikki nämä sarjan edelliset osat täältä, jatkaaksesi lisäohjeita uusien sovellusten luomiseen:

  1. Luo käyttöliittymäsovelluksia Linux-työpöydällä käyttämällä PyGObjectia - osa 1
  2. Advance PyGobject -sovellusten luominen Linuxille - osa 2

Pythonin moduulit ja kirjastot ovat erittäin hyödyllisiä. Sen sijaan, että kirjoitat monia alaohjelmia tekemään monimutkaisia töitä, jotka vievät paljon aikaa ja työtä, voit vain tuoda ne! Kyllä, tuo vain tarvitsemasi moduulit ja kirjastot ohjelmaasi ja voit säästää paljon aikaa ja vaivaa ohjelman loppuun saattamiseksi.

Pythonille on monia tunnettuja moduuleja, jotka löydät Python Module Index -sivulta.

Voit tuoda kirjastoja myös Python-ohjelmallesi, " gi.repository import Gtk " -rivillä tämä rivi tuo GTK-kirjaston Python-ohjelmaan, on monia muita kirjastoja, kuten Gdk, WebKit jne.

Advance GUI -sovellusten luominen

Luomme tänään 2 ohjelmaa:

  1. yksinkertainen verkkoselain; joka käyttää WebKit-kirjastoa.
  2. pöytäkone, joka käyttää avconv-komentoa; joka käyttää Pythonin os-moduulia.

En selitä, kuinka vetää ja pudottaa widgetejä Glade -suunnittelijasta tästä eteenpäin, kerron vain sinun luomiesi widgetien nimen, ja annan sinulle .glade tiedosto jokaiselle ohjelmalle ja Python-tiedosto varmasti.

Verkkoselaimen luomiseksi meidän on käytettävä WebKit -moottoria, joka on verkon avoimen lähdekoodin renderointimoottori, se on sama, jota käytetään Chrome / Chromium , saat lisätietoja siitä viralliselta Webkit.org-verkkosivustolta.

Ensin meidän on luotava käyttöliittymä, avattava Glade -suunnittelija ja lisättävä seuraavat widgetit. Lisätietoja widgetien luomisesta on tämän sarjan osassa 1 ja osassa 2 (yllä olevat linkit).

  1. Luo ikkuna1 -widget.
  2. Luo 'box1' ja 'box2' widget.
  3. Luo 'button1' ja 'button2' widget.
  4. Luo 'entry1' -widget.
  5. Luo scrolledwindow1-widget.

Kun olet luonut widgetit, saat seuraavan käyttöliittymän.

Ei ole mitään uutta, paitsi Vieritetty ikkuna -widget; tämä widget on tärkeä, jotta WebKit -moottori voidaan istuttaa sen sisälle. Voit käyttää Scrolled Window -widgetiä myös vierittämällä vaaka- ja pystysuunnassa selata verkkosivustoja.

Sinun on nyt lisättävä backbutton_clicked -käsittelijä Back -painikkeen clicked -signaaliin, refreshbutton_clicked käsittelijä Päivitä-painikkeeseen napsautettu signaali ja enterkey_clicked -käsittelijä syötteen aktivoitu -signaaliin.

Liitännän täydellinen .glade -tiedosto on täällä.

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

Kopioi nyt yllä oleva koodi ja liitä se kotikansiosi ui.glade -tiedostoon. Luo nyt uusi tiedosto nimeltä mywebbrowser.py ja kirjoita seuraava koodi siihen, kaikki selitykset ovat kommenteissa.

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

Tallenna tiedosto ja suorita se.

$ chmod 755 mywebbrowser.py
$ ./mywebbrowser.py

Ja tämän saat.

Voit etsiä WebKitGtk virallista dokumentaatiota löytääksesi lisää vaihtoehtoja.

Tässä osassa opit, kuinka paikalliset järjestelmäkomennot tai komentosarjat suoritetaan Python-tiedostosta os -moduulin avulla, mikä auttaa meitä luomaan yksinkertaisen näytön tallentimen työpöydälle käyttämällä avconv -komento.

Avaa Glade-suunnittelija ja luo seuraavat widgetit:

  1. Luo ikkuna1 -widget.
  2. Luo box1-widget.
  3. Luo painike1, 'painike2' ja 'painike3' widgetit.
  4. Luo 'entry1' -widget.

Kun olet luonut edellä mainitut widgetit, saat käyttöliittymän alapuolelle.

Tässä on täydellinen ui.glade -tiedosto.

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

Kopioi yllä oleva koodi tavalliseen tapaan ja liitä se kotihakemiston tiedostoon ui.glade , luo uusi tiedosto myrecorder.py ja kirjoita seuraava koodi sen sisällä (jokainen uusi rivi selitetään kommenteissa).

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

Suorita tiedosto nyt suorittamalla seuraavat komennot päätelaitteessa.

$ chmod 755 myrecorder.py
$ ./myrecorder.py

Ja sinulla on ensimmäinen työpöydän tallennin.

Löydät lisätietoja os -moduulista Python OS -kirjastosta.

Ja siinä kaikki, sovellusten luominen Linux-työpöydälle ei ole vaikeaa PyGObject -toiminnon avulla, sinun tarvitsee vain luoda käyttöliittymä, tuoda joitain moduuleja ja linkittää Python-tiedosto käyttöliittymään, ei mitään muuta, ei vähempää. PyGObject-verkkosivustolla on monia hyödyllisiä opetusohjelmia tämän tekemisestä:

Oletko yrittänyt luoda sovelluksia PyGObjectilla? Mitä ajattelet tekemästä niin? Mitä sovelluksia olet kehittänyt aiemmin?