Búðu til þinn eigin vefvafra og skrifborðsupptökuforrit með því að nota PyGobject - Part 3


Þetta er þriðji hluti seríunnar um að búa til GUI forrit undir Linux skjáborðinu með PyGObject. Í dag munum við tala um að nota nokkrar háþróaðar Python einingar og bókasöfn í forritum okkar eins og 'os', 'WebKit', 'requests' og önnur, auk annarra gagnlegra upplýsinga fyrir forritun.

Þú verður að fara í gegnum alla þessa fyrri hluta seríunnar héðan, til að halda áfram frekari leiðbeiningum um að búa til fleiri fyrirfram forrit:

  1. Búðu til GUI forrit undir Linux skjáborði með því að nota PyGObject – Part 1
  2. Búa til Advance PyGobject forrit á Linux – Part 2

Einingar og bókasöfn í Python eru mjög gagnleg, í stað þess að skrifa mörg undirforrit til að vinna flókin störf sem mun taka mikinn tíma og vinnu, geturðu bara flutt þau inn! Já, flyttu bara inn einingarnar og bókasöfnin sem þú þarft í forritið þitt og þú munt geta sparað mikinn tíma og fyrirhöfn til að klára forritið þitt.

Það eru margar frægar einingar fyrir Python, sem þú getur fundið á Python Module Index.

Þú getur líka flutt inn bókasöfn fyrir Python forritið þitt, frá “gi.repository import Gtk” flytur þessi lína GTK bókasafnið inn í Python forritið, það eru mörg önnur bókasöfn eins og Gdk, WebKit.. o.s.frv.

Að búa til fyrirfram GUI forrit

Í dag munum við búa til 2 forrit:

  1. Einfaldur vafri; sem mun nota WebKit bókasafnið.
  2. Skrifborðsupptökutæki sem notar 'avconv' skipunina; sem mun nota ‘os’ eininguna frá Python.

Ég mun ekki útskýra hvernig á að draga og sleppa græjum í Glade hönnuðinum héðan í frá, ég mun bara segja þér nafnið á græjunum sem þú þarft að búa til, auk þess mun ég gefa þér .glade skrá fyrir hvert forrit, og Python skrána örugglega.

Til að búa til vafra verðum við að nota \WebKit vélina, sem er opinn uppspretta flutningsvél fyrir vefinn, það er sú sama og er notuð í Chrome/Chromium, fyrir frekari upplýsingar um það geturðu vísað til opinberu Webkit.org vefsíðunnar.

Fyrst verðum við að búa til GUI, opna Glade hönnuðinn og bæta við eftirfarandi búnaði. Fyrir frekari upplýsingar um hvernig á að búa til græjur skaltu fylgja 1. hluta og 2. hluta af þessari röð (tenglar gefnir hér að ofan).

  1. Búðu til ‘window1’ græju.
  2. Búðu til 'box1' og 'box2' græju.
  3. Búðu til ‘button1’ og ‘button2’ græju.
  4. Búa til ‘entry1’ græju.
  5. Búðu til ‘scrolledwindow1’ græju.

Eftir að hafa búið til græjur færðu eftirfarandi viðmót.

Það er ekkert nýtt, nema \Skrollaður gluggi græjan; þessi græja er mikilvæg til að leyfa að WebKit vélin sé grædd inn í hana með því að nota \ >Skrollaður gluggi” búnaður þú munt líka geta fletta lárétt og lóðrétt á meðan þú vafrar um vefsíðurnar.

Þú verður nú að bæta \backbutton_clicked stjórnanda við Back hnappinn \clicked merki, \refreshbutton_clicked b>“ meðhöndlari á endurnýjunarhnappinn \smellt merki og \enterkey_clicked meðhöndlari í \virkjað merki fyrir færsluna .

Heildar .glade skrá fyrir viðmótið er hér.

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

Afritaðu nú kóðann hér að ofan og límdu hann í \ui.glade skrána í heimamöppunni þinni. Búðu til nýja skrá sem heitir \mywebbrowser.py og sláðu inn eftirfarandi kóða inni í honum, öll skýringin er í athugasemdunum.

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

Vistaðu skrána og keyrðu hana.

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

Og þetta er það sem þú munt fá.

Þú gætir leitað til WebKitGtk opinberra skjala til að uppgötva fleiri valkosti.

Í þessum hluta munum við læra hvernig á að keyra staðbundnar kerfisskipanir eða skeljaforskriftir úr Python skránni með því að nota 'os' eininguna, sem mun hjálpa okkur að búa til einfaldan skjáupptökutæki fyrir skjáborðið með því að nota 'avconv' skipun.

Opnaðu Glade hönnuðinn og búðu til eftirfarandi græjur:

  1. Búðu til ‘window1’ græju.
  2. Búðu til ‘box1’ græju.
  3. Búa til 'button1', 'button2' og 'button3' græjur.
  4. Búa til 'entry1' græju.

Eftir að hafa búið til ofangreindar búnaður færðu viðmótið fyrir neðan.

Hér er öll ui.glade skráin.

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

Eins og venjulega, afritaðu kóðann hér að ofan og límdu hann í skrána \ui.glade í heimaskránni þinni, búðu til nýja \myrecorder.py skrá og sláðu inn eftirfarandi kóða inni í honum (Hver ný lína er útskýrð í athugasemdum).

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

Keyrðu nú skrána með því að beita eftirfarandi skipunum í flugstöðinni.

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

Og þú fékkst fyrsta borðtölvuupptökutækið þitt.

Þú getur fundið frekari upplýsingar um 'os' eininguna á Python OS Library.

Og það er það, að búa til forrit fyrir Linux skjáborðið er ekki erfitt með því að nota PyGObject, þú verður bara að búa til GUI, flytja inn nokkrar einingar og tengja Python skrána við GUI, hvorki meira né minna. Það eru mörg gagnleg námskeið um að gera þetta á PyGObject vefsíðunni:

Hefur þú prófað að búa til forrit með PyGObject? Hvað finnst þér um að gera það? Hvaða forrit hefur þú þróað áður?