PyGobject'i Kullanarak Kendi 'Web Tarayıcı' ve 'Masaüstü Kaydedici' Uygulamalarınızı Oluşturun - Bölüm 3


Bu, PyGObject kullanarak Linux masaüstü altında GUI uygulamaları oluşturmaya ilişkin serinin 3. kısmıdır. Bugün 'os', 'WebKit', 'requests' ve gibi bazı gelişmiş Python modüllerini ve kitaplıklarını programlarımızda kullanmaktan bahsedeceğiz. diğerleri, programlama için diğer bazı yararlı bilgilerin yanı sıra.

Gereksinimler

Daha gelişmiş uygulamalar oluşturmaya yönelik daha fazla talimata devam etmek için serinin önceki tüm bölümlerini buradan gözden geçirmelisiniz:

  1. PyGObject Kullanarak Linux Masaüstü Altında GUI Uygulamaları Oluşturma – Bölüm 1
  2. Linux'ta İleri PyGobject Uygulamaları Oluşturma – Bölüm 2

Python'daki modüller ve kütüphaneler çok faydalıdır, çok fazla zaman ve çalışma gerektirecek bazı karmaşık işleri yapmak için birçok alt program yazmak yerine, bunları içe aktarabilirsiniz! Evet, ihtiyacınız olan modülleri ve kütüphaneleri programınıza aktarın; programınızı tamamlamak için çok fazla zaman ve emekten tasarruf edebileceksiniz.

Python için Python Modül Dizini'nde bulabileceğiniz birçok ünlü modül vardır.

Python programınız için kütüphaneleri de içe aktarabilirsiniz, “gi.repository import Gtk” kısmından bu satır GTK kütüphanesini Python programına aktarır, Gdk, WebKit.. vb. gibi başka birçok kütüphane vardır.

Gelişmiş GUI Uygulamaları Oluşturma

Bugün 2 program oluşturacağız:

  1. Basit bir web tarayıcısı; WebKit kütüphanesini kullanacak.
  2. 'avconv' komutunu kullanan bir masaüstü kaydedici; Python'un 'os' modülünü kullanacak.

Artık Glade tasarımcısında widget'ları nasıl sürükleyip bırakacağınızı açıklamayacağım, sadece oluşturmanız gereken widget'ların adını söyleyeceğim, ayrıca .glade dosyası ve elbette Python dosyası.

Basit Bir Web Tarayıcısı Oluşturma

Bir web tarayıcısı oluşturmak için, web için açık kaynaklı bir oluşturma motoru olan “WebKit” motorunu kullanmamız gerekecek; bu, 'de kullanılanla aynıdır. Chrome/Chromium hakkında daha fazla bilgi için resmi Webkit.org web sitesine başvurabilirsiniz.

Öncelikle GUI'yi oluşturmamız, Glade tasarımcısını açmamız ve aşağıdaki widget'ları eklememiz gerekecek. Widget'ların nasıl oluşturulacağı hakkında daha fazla bilgi için bu serinin Bölüm 1 ve Bölüm 2'sini izleyin (bağlantılar yukarıda verilmiştir).

  1. 'Pencere1' widget'ı oluşturun.
  2. 'Kutu1' ve 'kutu2' widget'ını oluşturun.
  3. 'Button1' ve 'button2' widget'ını oluşturun.
  4. 'Giriş1' widget'ını oluşturun.
  5. 'Kaydırılmış pencere1' widget'ını oluşturun.

Widget'ları oluşturduktan sonra aşağıdaki arayüzü elde edeceksiniz.

Kaydırılmış Pencere ” widget'ı dışında yeni bir şey yok; bu widget, WebKit motorunun içine yerleştirilmesine izin vermek açısından önemlidir; "Kaydırılmış Pencere " widget'ını kullanarak, aynı zamanda yatay ve dikey olarak kaydırma da yapabileceksiniz. web sitelerine göz atın.

Şimdi, Geri düğmesinin “tıklandı” sinyaline, “refreshbutton_clicked” işleyicisini “backbutton_clicked” işleyicisini eklemeniz gerekecek işleyicisini Yenile düğmesi “tıklandı sinyali” ve “enterkey_clicked ” işleyicisini giriş için “etkinleştirildi ” sinyaline yönlendirin.

Arayüze ilişkin .glade dosyasının tamamı burada.

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

Şimdi yukarıdaki kodu kopyalayıp ana klasörünüzdeki “ui.glade” dosyasına yapıştırın. Şimdi “mywebbrowser.py” adında yeni bir dosya oluşturun ve içine aşağıdaki kodu girin, tüm açıklamalar yorumlarda.

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

Dosyayı kaydedin ve çalıştırın.

chmod 755 mywebbrowser.py
./mywebbrowser.py

Ve elde edeceğiniz şey budur.

Daha fazla seçenek keşfetmek için WebKitGtk resmi belgelerine başvurabilirsiniz.

Basit Bir Masaüstü Kaydedici Oluşturma

Bu bölümde, 'os' modülünü kullanarak Python dosyasından yerel sistem komutlarını veya kabuk komut dosyalarını nasıl çalıştıracağımızı öğreneceğiz; bu, masaüstü için basit bir ekran kaydedici oluşturmamıza yardımcı olacaktır. 'avconv' komutu.

Glade tasarımcısını açın ve aşağıdaki widget'ları oluşturun:

  1. 'Pencere1' widget'ı oluşturun.
  2. 'Box1' widget'ını oluşturun.
  3. 'Button1', 'button2' ve 'button3' widget'larını oluşturun.
  4. 'Giriş1' widget'ını oluşturun.

Yukarıda belirtilen widget'ları oluşturduktan sonra, aşağıdaki arayüzü elde edeceksiniz.

İşte ui.glade dosyasının tamamı.

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

Her zamanki gibi yukarıdaki kodu kopyalayıp ana dizininizdeki “ui.glade” dosyasına yapıştırın, yeni bir “myrecorder.py” dosyası oluşturun ve aşağıdakini girin içindeki kod (Her yeni satır yorumlarda açıklanmıştır).

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

Şimdi terminalde aşağıdaki komutları uygulayarak dosyayı çalıştırın.

chmod 755 myrecorder.py
./myrecorder.py

Ve ilk masaüstü kayıt cihazınıza sahip oldunuz.

'os' modülü hakkında daha fazla bilgiyi Python İşletim Sistemi Kitaplığı'nda bulabilirsiniz.

İşte bu, PyGObject kullanarak Linux masaüstü için uygulamalar oluşturmak zor değil, sadece GUI'yi oluşturmanız, bazı modülleri içe aktarmanız ve Python dosyasını GUI'ye bağlamanız gerekiyor, ne daha fazlası ne daha azı. PyGObject web sitesinde bunu yapmaya ilişkin birçok faydalı eğitim bulunmaktadır:

PyGObject kullanarak uygulama oluşturmayı denediniz mi? Bunu yapmak hakkında ne düşünüyorsunuz? Daha önce hangi uygulamaları geliştirdiniz?