웹사이트 검색

PyGobject를 사용하여 자신만의 '웹 브라우저' 및 '데스크톱 레코더' 애플리케이션 만들기 - 3부


이것은 PyGObject를 사용하여 Linux 데스크톱에서 GUI 응용 프로그램을 만드는 방법에 관한 시리즈의 세 번째 부분입니다. 오늘은 'os', 'WebKit', 'requests' 및 '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. 간단한 웹 브라우저; WebKit 라이브러리를 사용합니다.
  2. 'avconv' 명령을 사용하는 데스크톱 레코더 Python의 'os' 모듈을 사용합니다.

이제부터 Glade 디자이너에서 위젯을 드래그 앤 드롭하는 방법에 대해서는 설명하지 않고, 생성해야 하는 위젯의 이름만 알려드리겠습니다. 추가로 .glade 각 프로그램 파일과 Python 파일이 필요합니다.

간단한 웹 브라우저 만들기

웹 브라우저를 만들려면 웹용 오픈 소스 렌더링 엔진인 "WebKit " 엔진을 사용해야 합니다. 이는 에서 사용되는 것과 동일합니다. Chrome/Chromium에 대한 자세한 내용은 공식 Webkit.org 웹사이트를 참조하세요.

먼저 GUI를 생성하고 Glade 디자이너를 열고 다음 위젯을 추가해야 합니다. 위젯을 만드는 방법에 대한 자세한 내용을 보려면 이 시리즈의 1부2부(위에 제공된 링크)를 따르세요.

  1. 'window1' 위젯을 생성합니다.
  2. 'box1', 'box2' 위젯을 생성합니다.
  3. 'button1' 및 'button2' 위젯을 만듭니다.
  4. 'entry1' 위젯을 생성합니다.
  5. 'scrolledwindow1' 위젯을 생성합니다.

위젯을 생성하면 다음과 같은 인터페이스가 나타납니다.

스크롤 창” 위젯을 제외하고는 새로운 것이 없습니다. 이 위젯은 WebKit 엔진이 내부에 이식될 수 있도록 하는 데 중요합니다. "스크롤 창" 위젯을 사용하면 수평 및 수직으로 스크롤할 수도 있습니다. 웹사이트를 탐색해 보세요.

이제 backbutton_clicked " 핸들러를 뒤로 버튼 "clicked " 신호, "refreshbutton_clicked "에 추가해야 합니다. 항목에 대한 "활성화" 신호에 대한 새로 고침 버튼 "clicked signal" 및 "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

그리고 첫 번째 데스크탑 레코더를 갖게 되었습니다.

Python OS 라이브러리에서 'os' 모듈에 대한 자세한 정보를 찾을 수 있습니다.

그게 전부입니다. PyGObject를 사용하면 Linux 데스크톱용 애플리케이션을 만드는 것이 어렵지 않습니다. GUI를 만들고 일부 모듈을 가져온 다음 Python 파일을 GUI와 연결하면 됩니다. 그 이상도 그 이하도 아닙니다. PyGObject 웹사이트에는 이 작업에 대한 유용한 튜토리얼이 많이 있습니다:

PyGObject를 사용하여 애플리케이션을 만들어 보셨나요? 그렇게 하는 것에 대해 어떻게 생각하시나요? 이전에 어떤 애플리케이션을 개발해 보셨나요?