Looge oma veebibrauser ja töölaua salvesti rakendused PyGobjecti abil - 3. osa


See on 3. osa sarjast GUI-rakenduste loomise kohta Linuxi töölaua all PyGObjecti abil. Täna räägime mõnede täiustatud Pythoni moodulite ja teekide kasutamisest oma programmides, näiteks ' os ', ' WebKit ', ' taotlused ja teised, lisaks programmeerimiseks kasulik teave.

Siit peate läbima kõik need seeria eelmised osad, et jätkata täiendavate juhiste loomist eelrakenduste loomiseks:

  1. GUI-rakenduste loomine Linuxi töölaua all PyGObjecti abil - 1. osa
  2. PyGobjecti eelrakenduste loomine Linuxis - 2. osa

Pythoni moodulid ja teegid on väga kasulikud. Selle asemel, et kirjutada palju alamprogramme keerukate tööde tegemiseks, mis võtab palju aega ja tööd, võite need lihtsalt importida! Jah, lihtsalt impordi vajalikud moodulid ja teegid oma programmi ja saate oma programmi lõpuleviimiseks palju aega ja vaeva kokku hoida.

Pythoni jaoks on palju kuulsaid mooduleid, mille leiate Pythoni moodulite registrist.

Te saate oma Pythoni programmi jaoks importida ka teeke, failist „ gi.repository import Gtk ” importib see rida GTK teeki Pythoni programmi, seal on palju muid teeke nagu Gdk, WebKit jne.

Eelnevate GUI-rakenduste loomine

Täna loome 2 programmi:

  1. lihtne veebibrauser; mis kasutab WebKiti teeki.
  2. töölaua salvesti, mis kasutab käsku ‘avconv’; mis kasutab Pythoni moodulit ’os’.

Ma ei hakka nüüd selgitama, kuidas Glade 'i disaineris vidinaid lohistada, vaid ütlen teile nende vidinate nime, mis teil on vaja luua, lisaks annan teile iga programmi jaoks fail .glade ja kindlasti Pythoni fail.

Veebibrauseri loomiseks peame kasutama mootorit\" WebKit ", mis on veebi jaoks avatud lähtekoodiga renderdamismootor, see on sama, mida kasutatakse jaotises Chrome / Chromium , selle kohta lisateabe saamiseks võite pöörduda ametlikule Webkit.org-i veebisaidile.

Kõigepealt peame looma graafilise kasutajaliidese, avama kujundaja Glade ja lisama järgmised vidinad. Vidinate loomise kohta lisateabe saamiseks järgige selle seeria 1. osa ja 2. osa (ülaltoodud lingid).

  1. Looge vidin 'window1'.
  2. Looge vidin „box1” ja „box2”.
  3. Looge vidin 'button1' ja 'button2'.
  4. Looge vidin ‘entry1’.
  5. Looge vidin 'scrolledwindow1'.

Pärast vidinate loomist saate järgmise liidese.

Midagi uut pole, välja arvatud\" keritud akna " vidin; see vidin on oluline selleks, et võimaldada WebKit mootori implanteerimist selle sisse, kasutades\" Keritud aken ”vidin saab veebisaitide sirvimise ajal ka horisontaalselt ja vertikaalselt kerida.

Nüüd peate lisama\" backbutton_clicked " käitleja signaali Back \" clicked " signaali,\" refreshbutton_clicked ”käitleja nupule Värskenda \" klõpsatud signaal "ja \" sisestusklahv_klõpsatud "käitleja kirje \" aktiveeritud "signaali .

Liidese täielik .glade fail on siin.

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

Nüüd kopeerige ülaltoodud kood ja kleepige see oma kodukataloogi\" ui.glade " faili. Looge nüüd uus fail nimega\" mywebbrowser.py " ja sisestage järgmine kood selle sees, kogu selgitus on kommentaarides.

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

Salvestage fail ja käivitage see.

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

Ja seda saate.

Rohkemate võimaluste leidmiseks võite kasutada WebKitGtk ametlikku dokumentatsiooni.

Selles jaotises õpime, kuidas käivitada Pythoni failist kohaliku süsteemi käske või shelliskripte, kasutades moodulit os , mis aitab meil luua töölauale lihtsa ekraanisalvesti, kasutades käsk avconv .

Avage kujundaja Glade ja looge järgmised vidinad:

  1. Looge vidin 'window1'.
  2. Looge vidin „box1”.
  3. Looge vidinad nupp1, nupp2 ja nupp3.
  4. Looge vidin ‘entry1’.

Pärast nimetatud vidinate kohal loomist saate liidese alla.

Siin on täielik fail ui.glade .

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

Nagu tavaliselt, kopeerige ülaltoodud kood ja kleepige see oma kodukataloogi faili\" ui.glade ", looge uus\" myrecorder.py " fail ja sisestage järgmine kood selle sees (iga uus rida on selgitatud kommentaarides).

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

Nüüd käivitage fail, rakendades terminalis järgmised käsud.

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

Ja saite oma esimese töölaua salvesti.

Mooduli ‘ os ’ kohta leiate lisateavet Pythoni OS-i raamatukogust.

Ja see on kõik, Linuxi töölauale rakenduste loomine pole rakenduse PyGObject abil keeruline, peate lihtsalt looma graafilise kasutajaliidese, importima mõned moodulid ja linkima Pythoni faili GUI-ga, ei midagi muud ega vähemat. Selle tegemise kohta on PyGObjecti veebisaidil palju kasulikke õpetusi:

Kas olete proovinud PyGObjecti abil rakendusi luua? Mida arvate selle tegemisest? Milliseid rakendusi olete varem välja töötanud?