Buat Aplikasi 'Peramban Web' dan 'Perekam Desktop' Anda Sendiri Menggunakan PyGobject - Bagian 3


Ini adalah bagian ketiga dari seri tentang membuat aplikasi GUI di desktop Linux menggunakan PyGObject. Hari ini kita akan membahas tentang penggunaan beberapa modul & pustaka Python tingkat lanjut dalam program kita seperti 'os', 'WebKit', 'request' dan lainnya, selain beberapa informasi berguna lainnya untuk pemrograman.

Persyaratan

Anda harus mempelajari semua bagian seri sebelumnya dari sini, untuk melanjutkan instruksi lebih lanjut dalam membuat aplikasi yang lebih maju:

  1. Membuat Aplikasi GUI di Desktop Linux Menggunakan PyGObject – Bagian 1
  2. Membuat Aplikasi PyGobject Tingkat Lanjut di Linux – Bagian 2

Modul & perpustakaan di Python sangat berguna, daripada menulis banyak sub-program untuk melakukan beberapa pekerjaan rumit yang akan memakan banyak waktu dan tenaga, Anda cukup mengimpornya! Ya, cukup impor modul & pustaka yang Anda perlukan ke program Anda dan Anda akan dapat menghemat banyak waktu dan tenaga untuk menyelesaikan program Anda.

Ada banyak modul terkenal untuk Python, yang dapat Anda temukan di Indeks Modul Python.

Anda juga dapat mengimpor perpustakaan untuk program Python Anda, dari “gi.repository import Gtk ” baris ini mengimpor perpustakaan GTK ke dalam program Python, ada banyak perpustakaan lain seperti Gdk, WebKit.. dll.

Membuat Aplikasi GUI Tingkat Lanjut

Hari ini, kami akan membuat 2 program:

  1. Peramban web sederhana; yang akan menggunakan perpustakaan WebKit.
  2. Perekam desktop menggunakan perintah 'avconv'; yang akan menggunakan modul 'os' dari Python.

Saya tidak akan menjelaskan cara drag & drop widget di desainer Glade mulai sekarang, saya hanya akan memberi tahu Anda nama widget yang perlu Anda buat, selain itu saya akan memberi Anda .glade untuk setiap program, dan file Python pastinya.

Membuat Peramban Web Sederhana

Untuk membuat browser web, kita harus menggunakan mesin “WebKit ”, yang merupakan mesin rendering sumber terbuka untuk web, sama dengan yang digunakan di Chrome/Chromium, untuk info lebih lanjut tentangnya, Anda dapat merujuk ke situs web resmi Webkit.org.

Pertama, kita harus membuat GUI, buka desainer Glade dan tambahkan widget berikut. Untuk informasi lebih lanjut tentang cara membuat widget, ikuti Bagian 1 dan Bagian 2 dari seri ini (tautan diberikan di atas).

  1. Buat widget 'jendela1'.
  2. Buat widget 'kotak1' dan 'kotak2'.
  3. Buat widget 'button1' dan 'button2'.
  4. Buat widget 'entri1'.
  5. Buat widget 'scrolledwindow1'.

Setelah membuat widget, Anda akan mendapatkan antarmuka berikut.

Tidak ada yang baru, kecuali widget “Jendela Gulir ”; widget ini penting agar mesin WebKit dapat ditanamkan di dalamnya, dengan menggunakan widget “Jendela Gulir ” Anda juga dapat menggulir secara horizontal dan vertikal saat Anda menelusuri situs web.

Anda sekarang harus menambahkan pengendali “backbutton_clicked ” ke sinyal tombol Kembalidiklik ”, “refreshbutton_clicked ” pengendali ke tombol Refresh “sinyal diklik” dan pengendali “enterkey_clicked ” ke sinyal “diaktifkan ” untuk entri.

File .glade lengkap untuk antarmuka ada di sini.

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

Sekarang salin kode di atas dan tempel di file “ui.glade ” di folder rumah Anda. Sekarang buat file baru bernama “mywebbrowser.py ” dan masukkan kode berikut di dalamnya, semua penjelasan ada di komentar.

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

Simpan file, dan jalankan.

chmod 755 mywebbrowser.py
./mywebbrowser.py

Dan inilah yang akan Anda dapatkan.

Anda dapat merujuk ke dokumentasi resmi WebKitGtk untuk menemukan opsi lainnya.

Membuat Perekam Desktop Sederhana

Di bagian ini, kita akan mempelajari cara menjalankan perintah sistem lokal atau skrip shell dari file Python menggunakan modul 'os', yang akan membantu kita membuat perekam layar sederhana untuk desktop menggunakan perintah 'avconv'.

Buka desainer Glade, dan buat widget berikut:

  1. Buat widget 'jendela1'.
  2. Buat widget 'kotak1'.
  3. Buat widget 'button1', 'button2' dan 'button3'.
  4. Buat widget 'entri1'.

Setelah membuat widget di atas, Anda akan mendapatkan antarmuka di bawah ini.

Berikut file ui.glade selengkapnya.

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

Seperti biasa, salin kode di atas dan tempel di file “ui.glade ” di direktori home Anda, buat file “myrecorder.py ” baru dan masukkan yang berikut ini kode di dalamnya (Setiap baris baru dijelaskan di komentar).

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

Sekarang jalankan file dengan menerapkan perintah berikut di terminal.

chmod 755 myrecorder.py
./myrecorder.py

Dan Anda mendapatkan perekam desktop pertama Anda.

Anda dapat menemukan informasi lebih lanjut tentang modul 'os' di Perpustakaan Python OS.

Selesai, membuat aplikasi untuk desktop Linux tidaklah sulit menggunakan PyGObject, Anda hanya perlu membuat GUI, mengimpor beberapa modul dan menautkan file Python dengan GUI, tidak lebih, tidak kurang. Ada banyak tutorial berguna tentang melakukan hal ini di situs web PyGObject:

Sudahkah Anda mencoba membuat aplikasi menggunakan PyGObject? Apa pendapat Anda tentang melakukan hal itu? Aplikasi apa yang pernah Anda kembangkan sebelumnya?