ウェブサイト検索

PyGobject を使用して独自の「Web ブラウザ」および「デスクトップ レコーダー」アプリケーションを作成する - パート 3


これは、PyGObject を使用して Linux デスクトップで GUI アプリケーションを作成するシリーズの第 3 回 パートです。今日は、「os」、「WebKit」、「requests」などのプログラムでの高度な Python モジュールとライブラリの使用について説明します。その他、プログラミングに役立つ情報もいくつかあります。

要件

より高度なアプリケーションを作成するための指示を続けるには、ここからシリーズの前の部分をすべて参照する必要があります。

  1. PyGObject を使用して Linux デスクトップで GUI アプリケーションを作成する – パート 1
  2. Linux での高度な PyGobject アプリケーションの作成 – パート 2

Python のモジュールとライブラリは非常に便利です。多くの時間と労力がかかる複雑なジョブを実行するために多くのサブプログラムを作成する代わりに、それらをインポートするだけで済みます。はい、必要なモジュールとライブラリをプログラムにインポートするだけで、プログラムを完成させるための時間と労力を大幅に節約できます。

Python には有名なモジュールが多数あり、Python モジュール インデックスで見つけることができます。

Python プログラムのライブラリもインポートできます。「gi.repository import Gtk 」からこの行で GTK ライブラリを Python プログラムにインポートします。Gdk、WebKit など、他にも多くのライブラリがあります。

高度な GUI アプリケーションの作成

今日は 2 つのプログラムを作成します。

  1. シンプルな Web ブラウザ。これは WebKit ライブラリを使用します。
  2. 「avconv」コマンドを使用するデスクトップレコーダー。これは、Python の「os」モジュールを使用します。

今後、Glade デザイナーでウィジェットをドラッグ アンド ドロップする方法については説明しません。作成する必要があるウィジェットの名前だけを説明します。さらに、 > 各プログラムの .glade ファイルと、確かに Python ファイルです。

単純な Web ブラウザの作成

Web ブラウザを作成するには、「WebKit 」エンジンを使用する必要があります。これは Web 用のオープンソース レンダリング エンジンであり、 で使用されているものと同じです。 Chrome/Chromium の詳細については、公式 Webkit.org Web サイトを参照してください。

まず、GUI を作成し、Glade デザイナーを開いて次のウィジェットを追加する必要があります。ウィジェットの作成方法の詳細については、このシリーズのパート 1パート 2 を参照してください (上記のリンク)。

  1. 「window1」ウィジェットを作成します。
  2. 「box1」ウィジェットと「box2」ウィジェットを作成します。
  3. 「button1」ウィジェットと「button2」ウィジェットを作成します。
  4. 「entry1」ウィジェットを作成します。
  5. 「scrolledwindow1」ウィジェットを作成します。

ウィジェットを作成すると、次のインターフェイスが表示されます。

スクロール ウィンドウ 」ウィジェット以外に新しいものはありません。このウィジェットは、WebKit エンジンを内部に埋め込むために重要です。「スクロール ウィンドウ 」ウィジェットを使用すると、水平および垂直にスクロールすることもできます。ウェブサイトを閲覧します。

ここで、「backbutton_clicked 」ハンドラーを 戻る ボタン「clicked 」シグナル「refreshbutton_clicked 」に追加する必要があります。更新ボタン「clicked シグナル」へのハンドラーと、エントリの「activated 」シグナルへの「enterkey_clicked 」ハンドラー。

インターフェースの完全な .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 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>

次に、上記のコードをコピーして、ホーム フォルダーの「ui.glade 」ファイルに貼り付けます。ここで、「mywebbrowser.py 」という名前の新しいファイルを作成し、その中に次のコードを入力します。すべての説明はコメントにあります。

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

ファイルを保存して実行します。

chmod 755 mywebbrowser.py
./mywebbrowser.py

そしてこれが得られるものです。

さらに多くのオプションを見つけるには、WebKitGtk 公式ドキュメントを参照してください。

シンプルなデスクトップレコーダーの作成

このセクションでは、「os」モジュールを使用して Python ファイルからローカル システム コマンドまたはシェル スクリプトを実行する方法を学習します。これは、 「avconv」コマンド。

Glade デザイナーを開き、次のウィジェットを作成します。

  1. 「window1」ウィジェットを作成します。
  2. 「box1」ウィジェットを作成します。
  3. 「button1」、「button2」、「button3」ウィジェットを作成します。
  4. 「entry1」ウィジェットを作成します。

上記のウィジェットを作成すると、以下のインターフェイスが表示されます。

完全な 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>

いつものように、上記のコードをコピーしてホーム ディレクトリのファイル「ui.glade 」に貼り付け、新しい「myrecorder.py 」ファイルを作成して次のように入力します。その中にコードが含まれています (すべての新しい行はコメントで説明されています)。

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

次に、ターミナルで次のコマンドを適用してファイルを実行します。

chmod 755 myrecorder.py
./myrecorder.py

そして、あなたは初めてのデスクトップレコーダーを手に入れました。

os」 モジュールの詳細については、Python OS ライブラリを参照してください。

PyGObject を使用して Linux デスクトップ用のアプリケーションを作成するのは難しくありません。GUI を作成し、いくつかのモジュールをインポートし、Python ファイルを GUI にリンクするだけで済みます。それ以上でもそれ以下でもありません。 PyGObject Web サイトには、これを行うための役立つチュートリアルが多数あります。

PyGObject を使用してアプリケーションを作成してみましたか?そうすることについてどう思いますか?これまでにどのようなアプリケーションを開発したことがありますか?