PyGTK 3: mini GUI tutorial with Python + GTK + 3

We are going to make a small program with PyGTK 3.0 that also works for PyGTK 3.4. This little GUI will teach you how to divide a program into two or more files.

You can visit Sebastian Pölsterl's tutorial on the new PyGTK 3, here is the new tutorial, I leave the link:

http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html

This is Sebastian's blog.

http://k-d-w.org/node/88

A criticism of this tutorial by Sebastian is that it does not teach how to divide a program into parts or into several files, it would have been good if he showed an example of how to do it with PyGTK 3.

All large and complex programs are divided into many files and the files are even placed in other directories, that is, they are located in different folders.

Let's start with the small example:

Here is the writing code in a single file called gui.py. We open the Gedit text editor or the editor we use the most, copy the code below and save it as gui.py

from gi.repository import Gtk class gui (): def on_open_clicked (self, button): print "\" Open \ "button was clicked" def on_close_clicked (self, button): print "Closing application" Gtk.main_quit () def __init__ (self): self.window = Gtk.Window () self.window.connect ('delete-event', Gtk.main_quit) self.box = Gtk.Box () self.window.add (self.box) self. button = Gtk.Button (label = 'Open') self.button.connect ("clicked", self.on_open_clicked) self.box.pack_start (self.button, True, True, 0) self.button = Gtk.Button ( label = 'Close') self.button.connect ("clicked", self.on_close_clicked) self.box.pack_start (self.button, True, True, 0) self.window.show_all () Gtk.main () if __name__ == '__main__': gui = gui ()

pediment

def on_open_clicked (self, button): print "\" Open \ "button was clicked"

It is a function that is activated in the terminal when we click the open button. The signal to activate it is:

self.button.connect ("clicked", self.on_open_clicked) def on_close_clicked (self, button): print "Closing application" Gtk.main_quit ()

It is a function that is activated when we click on the close button.

close the program we run.

the signal to activate it is

self.button.connect ("clicked", self.on_close_clicked) from gi.repository import Gtk ### we invoke PyGTK libraries ### class gui (): ### class definition called gui is the main class # ##

Widgets declaration: a widgets is a program predetermined by the graphical interface libraries that we use. For example, a widgets is a button, a window, a box, etc. These are the widgets that we declare in our program.

self.window = Gtk.Window () ### window ### self.box = Gtk.Box () ### box #### self.button = Gtk.Button (label = 'Open') ### # open button #### self.button = Gtk.Button (label = 'Close') #### close button #### self.window.add (self.box) #### the box is contained in the window called window #### self.box.pack_start (self.button, True, True, 0) ##### the button is contained in the box called box ### self.window.show_all () ## # we show the whole window ### gui = gui () ### create a gui object ####

We place our program in a folder called simple in our case on the desktop

fert

We open the folder with the terminal, in my case I use Nemo from Linux Mint 14.

closed

To compile we put in the terminal python gui.py

see the picture.

terminal

Now we can see our small program or new widget created with the PyGTK 3 libraries

It is a simple window with two buttons.

Untitled

Now we divide the program into three parts, below I leave the code of the three files.

First gui.py file

from gi.repository import Gtk from destroy import destroy from io import io class gui (destroy, io): def __init __ (self): self.window = Gtk.Window () self.window.connect ('delete-event', Gtk .main_quit) self.box = Gtk.Box () self.window.add (self.box) self.button = Gtk.Button (label = 'Open') self.button.connect ("clicked", self.on_open_clicked) self.box.pack_start (self.button, True, True, 0) self.button = Gtk.Button (label = 'Close') self.button.connect ("clicked", self.on_close_clicked) self.box.pack_start ( self.button, True, True, 0) self.window.show_all () Gtk.main () if __name__ == '__main__': gui = gui ()

Second io.py file

class io: def on_open_clicked (self, button): print "\" Open \ "button was clicked"

Third file destroy.py

from gi.repository import Gtk class destroy: def on_close_clicked (self, button): print "Closing application" Gtk.main_quit ()

We place the three files in the same folder in our case, the folder is called simple divided.

tailored

To compile the three files. We open the folder with the terminal and simply put it back in the terminal

python gui.py

Modifications made to the gui.py code

from destroy import destroy ### statement to import our file destroy.py ### from io import io ### statement to import our file io.py ### class gui (destroy, io): #### to the class main we add the subclasses destroy and io ####

You can see that the sentence

def on_open_clicked (self, button): print "\" Open \ "button was clicked"

It is not in gui.py, it is in the io.py file

Sentence

def on_close_clicked (self, button):

print "Closing application"
Gtk.main_quit ()

it is located in the destroy.py file

Thus we can divide a program into many files located in different directories at the same time.

On the other hand, Python is a pillar of free software, and is adapted to work with GTK 3.6 /3.8, its name is PyGTK. Python's adaptation for KDE is called PyQT.

Python is adapted for Mac OS and WINDOWS.

I hope this PyGTK3 mini tutorial has been helpful to you. They can make all the constructive criticisms they want.

I also know some Gtk 3.4 /3.6 and Vala GTK 3.4 / 3.6.

http://www.youtube.com/watch?v=9ckRn_sx8CE

Lastly, KDE users apologize for not doing a mini tutorial for KDE.


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   rots87 said

    In kde I prefer to use kdevelop (I think that's what it's called) to create the gui at ease but I still have a hard time finding the processes to make it happen x thing: '(

  2.   st0rmt4il said

    Great for those of us who use Python: D!

    Regards!

  3.   Pablo said

    Hello, I have been following this community for a long time and I am not very sure if this is the first time I have commented or I have already done it before 😀 (I am not very given to writing comments on the web really). The thing is that I do it to leave a suggestion to Elav and KZKG ^ Gaara as administrators, and I think it would be a good idea to add a plugin for syntax coloring now that lately I see more posts with code in different programming languages. I know there are quite a few plugins but I haven't tried any since I'm not a wordpress user, so I leave you to think about the viability of the request. I take this opportunity to ask the rest of the readers what they think of the idea, because I know that there are people out there who prefer to read the code without any adornment. I apologize if this has already been commented on here and it was rejected for some reason, as I do not remember seeing a discussion on the subject.

    1.    marianogaudix said

      The truth is I would like to have the option to color the syntax to highlight the code of the programming languages.
      That would help users who want to learn programming languages.

      But hey, I'm also comfortable with the forum and that we can discuss and learn together.

      1.    eliotime3000 said

        GNU Emacs is more comfortable, because at least you have to choose in which programming language checker you want to work (if you don't want more weight for your processor, use GNU Nano and enjoy minimalism at its best).

        1.    marianogaudix said

          Elio we are talking about WordPress. Implemented on the blog Desde Linux. It does not have the functions to color the letters of the posts.

          1.    eliotime3000 said

            Oh I'm sorry.

        2.    pandev92 said

          Naaa emacs is comfortable for those who have 84 fingers XD .., normal people, textmate, sublimetext or notepad ++ xd

          1.    eliotime3000 said

            The implausible thing is not having learned typing, which is required to be able to handle GNU Emacs and its keyboard shortcuts well. In addition, its GUI makes it easy for you to use its menus (it can be used in Windows, but it is not recommended to do it with the normal mode but with the command prompt mode so that win32 does not boycott your script).

  4.   Carper said

    Very cool tutorial. But by the way, the python source code is not compiled, it is an interpreted language.

    1.    giskard said

      It can be compiled to pseudo code. It is not machine language but bytes that represent something to the interpreter, but the process is called compiled as well. In this sense, it is possible to say that something is compiled.

  5.   hty said

    Perhaps it is better to learn pytgk2 because the latest version available for Windows is 2.24. Series 3 is conspicuous by its absence. And the bad tongues say that gnome breaks all the apis in each new version.

    1.    marianogaudix said

      I program a mockup with GTK 3.4 / 3.6 and the truth is that they break your patience and your head, you have to rewrite the code, now I understand why the Linux Mint people complain about GTK and the GNOME project.
      To those of MINT I agree with GTK 2.4 this did not happen.

  6.   Carlos said

    Good tutorial and references.
    Just a detail, since code has been put in, in Python indentations are mandatory and should be respected in the example code.

    Regards!

    1.    marianogaudix said

      Can you explain what the mandatory identifications in Python consist of? To tell you the truth, I have never heard that. I am badly used to the PyGTK 2/3 forums in English and maybe I overlook it.

      1.    giskard said

        In Python you don't use keys like in C or begin / end blocks like in Pascal, but everything is understood through the indentation you give to the code. That is, the blocks are recognized by being indented. It's a feature that I particularly love. You avoid writing keys and things like that.

        1.    pandev92 said

          I just don't like that, it seems simpler to put two little keys or a std :: endl ;, than being seen if the xd line is well tabulated

          1.    Felipe said

            : p Your programming teacher will put a 0 for you. Or worse they will fire you from your job. What matters most is that the code is readable with all that that implies

          2.    pandev92 said

            ending with closing braces, it makes me much more readable XD ..

          3.    giskard said

            Really???


            int main(int argc, char *argv[]){program_name = argv[0];while ((argc > 1) && (argv[1][0] == '-')) {switch (argv[1][1]) {case 'v':verbose = 1; break;case 'o':out_file = &argv[1][2];break;case 'l':line_max = atoi(&argv[1][2]);break;default:fprintf(stderr,"Bad option %s\n", argv[1]);usage();}++argv;--argc;} if (argc == 1) {do_file("print.in");} else {while (argc > 1) {do_file(argv[1]);++argv;--argc;}}return (0);}

            You see? Without indentations it is not very well understood. And that's an easy one. With a more complex one, only the compiler understands it. The thing is, since you HAVE to indent anyway (for humans to understand the code) why would you have to be redundant and use separators? Enough with indentation and that's it.

          4.    pandev92 said

            Of course, nothing is understood, because you are not respecting the rules of good writing for a program in c / c ++. What you did is valid for anything, such as nesting a function, inside a function inside another function that is inside another, then I want to see you xd if you are able to understand it.

          5.    pandev92 said

            by the way, with two looks, that code is easily understandable xD

          6.    giskard said

            What I did I did on purpose to show you that without indentation, even though it compiles, it is extremely difficult to understand any code. So you have 2 rules: Indent and encompass with delimiters. But that is redundant. In Python such code is simply not accepted by the interpreter. And you only have one rule: Indent. Easy.
            But hey, everyone with their tastes.

          7.    Atheyus said

            Both are good, the indented and the non-indented, in my opinion I prefer the semicolon style or ruby, similar to python but the indentation is not necessary.

            This is how it is better understood: P:

            echo 'int main (int argc, char * argv []) {program_name = argv [0]; while ((argc> 1) && (argv [1] [0] ==' - ')) {switch (argv [ 1] [1]) {case 'v': verbose = 1; break; case 'o': out_file = & argv [1] [2]; break; case 'l': line_max = atoi (& argv [1] [2]); break; default: fprintf (stderr, »Bad option% s \ n », argv [1]); usage ();} ++ argv; –argc;} if (argc == 1) {do_file (" print.in ");} else {while (argc> 1) { do_file (argv [1]); ++ argv; –argc;}} return (0);} '| perl -p -e 's / \ {/ \ {\ n \ t / g; s / \; / \; \ n \ t / g; s / \ t \} / \} / g;'

            regards

      2.    giskard said

        I think Carlos means that where the code comes out there are no indents. That with copy & paste just won't work. I don't know if the tag exists when creating a post to enter language code. It would be good if they put it if it does not exist.

        1.    giskard said

          I already saw what the problem is: the CODE Tag removes all spaces and tabs (it shouldn't do that !!!) But if you put a nbsp on it then the code looks good. A0 in hex (160 in dec) although I think it might depend on the font (I don't know). If it is used then it comes out like this:

          def fib(n):
              a, b = 0, 1
              while a < n:
                  print(a)
                  a, b = b, a+b

          That in my tests it looks good, but I don't have a preview when I post answers (and there should be that !!!) If it doesn't come out, it's not my fault culpa

          1.    marianogaudix said

            Look at the examples that Sebastian Pölsterl puts in his PyGTK 3 tutorial, Sebastian does not place labels.

            Example :

            http://python-gtk-3-tutorial.readthedocs.org/en/latest/entry.html#example

            you can see all of Sebastian's tutorial.

          2.    giskard said

            I do not know what you mean. What I am saying is that here, in the posts, it is not possible to use the HTML Tag «CODE» so that what you put as code and it comes out well indented. On the page you refer, if you look at the page sources, you will see that it does not use CODE but uses other HTML delimiters.
            It is not against the code that you put but rather pointing out a flaw in the posting system of this site. Which, perhaps, admins can fix.
            When I talk about tags I am obviously talking about HTML, not Python. In any case, if you put code without indentation in Python it just won't work. If a newbie comes and copies the code as it appears in this post and tries to run it, he will fail. You may be frustrated as you are a newbie. Again, the fault is not yours; and in my immediate previous answer what I did was give a way to solve the problem from the user-who-posts level.

          3.    marianogaudix said

            You're absolutely right, I should have uploaded photos instead of copying the code.
            to show how statements are properly ordered in PyGTK 3.

  7.   Felipe said

    To program with python I recommend using Eclipse with the PyDev plugin, or the Pychar m

  8.   louis said

    As mentioned above, that's exactly why I don't like python, because of the indentations. As we saw, doing copy & paste will not work, which does not happen with other languages ​​such as C, Java, PHP, etc.

    The readability thing, we apply a code beautifier (like http://indentcode.net/ ) and ready,

    The ugly thing is fixed, but if there is no indentation and the logic is altered, we sound ...

  9.   Carlos said

    I am new to PyGTK, is it possible to interact with shell scripts in this language?

    1.    Hello said

      Thanks for the tutorial.

      Greetings.