Giter Site home page Giter Site logo

sebp / pygobject-tutorial Goto Github PK

View Code? Open in Web Editor NEW
392.0 35.0 161.0 2.92 MB

Tutorial for using GTK+ 3 in Python

Home Page: https://python-gtk-3-tutorial.readthedocs.io/

License: GNU Lesser General Public License v2.1

Makefile 19.99% Python 80.01%
pygobject tutorial python gtk3 gnome

pygobject-tutorial's People

Contributors

abcleanonme avatar cjmayo avatar cydanil avatar danyeaw avatar dependabot[bot] avatar devjac avatar dharmatech avatar gianmt avatar haaninjo avatar hadware avatar kam193 avatar lazka avatar mcrapet avatar mozbugbox avatar nazgul77 avatar paretje avatar rffontenelle avatar sam-m888 avatar samdroid-apps avatar sebp avatar shivdhar avatar soulou avatar sunyatazero avatar takeshi-aihana avatar taraskuzyo avatar timgates42 avatar tingping avatar tshepang avatar vaurelios avatar xoristzatziki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pygobject-tutorial's Issues

Glade example to include ComboBox

in particular, a ComboBox created with new_with_model_and_entry.
I've translated the example in chapter 13 into a glade file, but the first combobox, the one with the free-entry text, I do not manage to construct with pure glade.
the first catch was adding the CellRendererText.
but I do not manage to make the internal entry editable, even if it is marked editable, I can't type in it.

this is my glade file, which I would assume equivalent to the example in chap13

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.20.0 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkListStore" id="country_store">
    <columns>
      <!-- column-name gchararray1 -->
      <column type="gchararray"/>
    </columns>
    <data>
      <row>
        <col id="0" translatable="yes">Austria</col>
      </row>
      <row>
        <col id="0" translatable="yes">Brazil</col>
      </row>
      <row>
        <col id="0" translatable="yes">Belgium</col>
      </row>
      <row>
        <col id="0" translatable="yes">France</col>
      </row>
      <row>
        <col id="0" translatable="yes">Germany</col>
      </row>
      <row>
        <col id="0" translatable="yes">Switzerland</col>
      </row>
      <row>
        <col id="0" translatable="yes">United Kingdom</col>
      </row>
      <row>
        <col id="0" translatable="yes">United States</col>
      </row>
      <row>
        <col id="0" translatable="yes">Uruguay</col>
      </row>
    </data>
  </object>
  <object class="GtkListStore" id="name_store">
    <columns>
      <!-- column-name gint1 -->
      <column type="gint"/>
      <!-- column-name gchararray1 -->
      <column type="gchararray"/>
    </columns>
    <data>
      <row>
        <col id="0">1</col>
        <col id="1" translatable="yes">Billy Bobo</col>
      </row>
      <row>
        <col id="0">2</col>
        <col id="1" translatable="yes">Joey Jojo</col>
      </row>
      <row>
        <col id="0">3</col>
        <col id="1" translatable="yes">Rob McRoberts</col>
      </row>
      <row>
        <col id="0">11</col>
        <col id="1" translatable="yes">Billy Bob Junior</col>
      </row>
      <row>
        <col id="0">12</col>
        <col id="1" translatable="yes">Sue Bob</col>
      </row>
      <row>
        <col id="0">31</col>
        <col id="1" translatable="yes">Xavier McRoberts</col>
      </row>
    </data>
  </object>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="title" translatable="yes">Combobox Example</property>
    <child>
      <object class="GtkBox">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">6</property>
        <child>
          <object class="GtkComboBox" id="name_combo">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="model">name_store</property>
            <property name="has_entry">True</property>
            <property name="entry_text_column">1</property>
            <signal name="changed" handler="on_name_combo_changed" swapped="no"/>
            <child>
              <object class="GtkCellRendererText" id="name_renderer"/>
              <attributes>
                <attribute name="text">1</attribute>
              </attributes>
            </child>
            <child internal-child="entry">
              <object class="GtkEntry">
                <property name="can_focus">False</property>
                <property name="placeholder_text" translatable="yes">type, or choose</property>
              </object>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkComboBox" id="country_combo">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="model">country_store</property>
            <property name="id_column">0</property>
            <signal name="changed" handler="on_country_combo_changed" swapped="no"/>
            <child>
              <object class="GtkCellRendererText" id="country_renderer"/>
              <attributes>
                <attribute name="text">0</attribute>
              </attributes>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
        <child>
          <object class="GtkComboBoxText" id="currencies_combo">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <items>
              <item translatable="yes">Euro</item>
              <item translatable="yes">US Dollars</item>
              <item translatable="yes">British Pound</item>
              <item translatable="yes">Japanese Yen</item>
              <item translatable="yes">Russian Ruble</item>
              <item translatable="yes">Mexican peso</item>
              <item translatable="yes">Swiss franc</item>
            </items>
            <signal name="changed" handler="on_currency_combo_changed" swapped="no"/>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">2</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
  </object>
</interface>

Flowbox example doesn't show colors

override_background_color is deprecated, and doesn't work.
Documentation says:
Deprecated since version 3.16: This function is not useful in the context of CSS-based rendering. If you wish to change the way a widget renders its background you should use a custom CSS style, through an application-specific Gtk.StyleProvider and a CSS style class. You can also override the default drawing of a widget through the Gtk.Widget ::draw signal, and use Cairo to draw a specific color, regardless of the CSS style.

I don't think things mentioned in documentation are the best way to do it in this case, so I used Gtk.ColorButton there, but it's probably not the same thing as intended, cause it opens color change window on click. What would be the best way to do it?

Feature request: section showing how to draw lines and simple shapes

An example showing how to draw lines and simple shapes was one of the first things I looked for in this tutorial but was disappointed not to find.

I suggest a window with a few input fields to specify x,y pairs of points/vertices, and then maybe a button to draw a triangle using those points as the corners of the triangle.

Split tutorial in PyGObject and GTK+ 3 parts

I propose splitting the tutorial in two parts:

  1. PyGObject documentation, describing the gi API (require_version etc.), GObject, Porting from old static bindings, properties, signals, threading, string handling

  2. Gtk+ 3 / Glib documentation, describing the various widgets, how to create your own widget etc., threading, main loop

Because: This would make the tutorial more useful for users of other GI modules like GStreamer/Clutter. It also would make it easier to write new docs for other modules since they can reference the PyGObject parts.

I can provide a patch if this is a welcome change.

FlexBox example is not working

FlexBox example is not working properly due to deprecated function override_background_color

I like to submit a pull request for the code ..

spinner example clarification

The spinner example shows only how to use it in case a user intentionally starts and stops the spinner. Does not show how to use it in real coding. In other words does not show how to indicate something (ex. a calculation) is in progress. Using start() and stop() in the same function (def) will show nothing. i.e.:

def calculate_something(self):
    self.spinner.start()
    for i in range(10000):
        dosomething()
    self.spinner.stop()

does not show spinning at all...

AttributeError in Application Example

I am experiencing an AttributeError at examples/application_example:97

$ python3 application_example.py 
Traceback (most recent call last):
  File "application_example.py", line 141, in <module>
    app = Application()
  File "application_example.py", line 97, in __init__
    self.add_main_option("test", ord("t"), GLib.OptionFlags.NONE,
AttributeError: 'Application' object has no attribute 'add_main_option'
  • Python 3.4.3
  • Gtk 3.10.8
  • Ubuntu 14.04.4 LTS (64)

I tried to investigate the GtkApplication API documentation but I still have no idea where this method should be.

Gtk.Stack does allow setting the visible child

In layout.txt it is written:

Gtk.Stack does not provide a means for users to change the visible child.

However, as of version 3.10, Gtk.Stack allows setting the visible child using: set_visible_child(child).

Cursor Shape

How I will change the cursor shape and color of multi-line textarea?

Plans to expand this to PyGObject ?

This is more a question than a real issue but I wished to know if there were any plans to expand these docs to the whole GObject API (such as GLib, Gdk, Gio, Cairo and Clutter).
I wanted to write docs for these APIs but with a full-time job and many other projects going on, it seems to be a pretty huge task. Also, I have little to no experience dealing with GObject stuff outside Gtk and if I were to write some docs, I'd like them to be validated by someone who knows the subject more than I do.
If this tutorial was expanding to the whole GObject API, I'd happily contribute to it, otherwise I don't really feel like starting a whole new project on my own.

layout.txt - Grid

I think this section could do with some further explanation of the methods attach() and attach_next_to(). I would suggest (modified from the GTK documentation):

The attach() method takes five parameters:

attach(child, left, top, width, height)

The "child" parameter is the widget to add, whilst "left" is the column number to attach the left side of child to and "top" indicates the row number to attach the top side of child to. The "width" and "height parameters indicate the number of columns that the child will span, and the number of rows that the child will span, respectively.

The attach_next_to() method also takes five parameters, which are:

  • child (Gtk.Widget) – the widget to add
  • sibling (Gtk.Widget or None) – the child of self that the child will be placed next to, or None to place the child at the beginning or end
  • side (Gtk.PositionType) – the side of sibling that child is positioned next to
  • width (int) – the number of columns that child will span
  • height (int) – the number of rows that child will span

I'm not helping you :)

hi, I just saw a post from you on planet gnome and came here to see if there was something I could help.

is there a "helping" or "TODO" section?

how can I help you to improve the tutorial?

bye and thanks for your work!

Packaging

A chapter about packaging would be really useful in my opinion. I am currently trying to find out how this is done and most tutorials focus on command-line tools that are distributed over the PyPI. It would be nice if there were a tutorial that shows how to make a deb or rpm that integrates into a distribution (a icon in the dash; starting the program by entering the name into the terminal).

first line

The "#!/usr/bin/python" as a first line is only needed if the file (aka the script) is going to be executed (aka is going to be an executable) under *NIX'es and, sometimes, for some clarification (because of python and python3). There is no such need in MS Windows or if the file is going to be used as a library only. (Sometimes it is a better idea not to have such a line in case the file does nothing if it is "executed").

Missing Doc for Paths

I started writing my first GTK app the other day and was struggling with creating a default selection for an IconView I had created. Many of the methods used in GTK have a "path" argument but this argument is not defined in the docs anywhere (for example, iconview.select_path()).

I was able to look at the C docs and through a little bit of trial an error I was able to figure out to select the first item in an IconView by default I would need the following code:

iconview.select_path(Gtk.TreePath(1))

I believe PyGTK allowed you to .select_path("1") but PyGObject requires you to create a TreePath wrapper first. I imagine other people will potentially encounter this issue, so it may be a good idea to include some documentation on Paths and TreePaths. For example, it is not clear to me if there is some alternative to a TreePath for "Trees" such as a list of Icons in an IconView, where each node has only one child.

I'm sorry that I do not have the technical expertise to write documentation myself.

Examples throw dk-CRITICAL and Gdk-WARNING when run

The following messages prints when running either of the first two examples in python.exe:
(python.exe:4124): Gdk-CRITICAL **: gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed

(python.exe:4124): Gdk-CRITICAL **: gdk_window_new: assertion 'GDK_IS_WINDOW (parent)' failed

(python.exe:4124): Gdk-WARNING **: gdk_input_wintab_init: gdk_window_new failed

I am running on Windows 7, python 2.7 installed. May be due to having more than one monitor? (I have 3 Monitors)

The program then proceeds to run normally, showing the window and buttons (in the case of the second example). I Find this odd when this is supposedly a "critical" error...

Wrap not working on labels in dialogs/window

The example here https://python-gtk-3-tutorial.readthedocs.io/en/latest/label.html does not render correctly on my machine. Instead of wrapping nicely it takes up the entire screen.

Should look like this:
image

Instead it looks like this:
screen shot 2017-10-17 at 4 32 20 pm

There is an outdated Stackoverflow article on this but it uses Gtk.Table which is depreciated (and not in the example in the tutorial). Curious if this is a bug or if there is something else going on.

I am on macOS with Python 2.7.14, GTK+ 3.22.24, and PyGObject 3.26.0

include example of how to get the required TargetEntry for drag and drop

I wanted to build an app which accepts drags. I looked up the drag and drop tutorial but it wasn't clear to me how I would make my app accept drags from other applications. Also, I needed to produce the necessary TargetEntries which I didn't know how to do.

The following example is ported from the pygtk tutorial but uses pygi. Maybe it's possible to include that somehow in the current tutorial.

#!/usr/bin/env python
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

def motion_cb(wid, context, x, y, time):
    Gdk.drag_status(context, Gdk.DragAction.COPY, time)
    return True

def drop_cb(wid, context, x, y, time):
    l.set_text('\n'.join([str(t) for t in context.list_targets()]))
    context.finish(True, False, time)
    return True

w = Gtk.Window()
w.set_size_request(200, 150)
w.drag_dest_set(0, [], 0)
w.connect('drag-motion', motion_cb)
w.connect('drag-drop', drop_cb)
w.connect('destroy', lambda w: Gtk.main_quit())
l = Gtk.Label()
w.add(l)
w.show_all()

Gtk.main()

Cannot build Pygobject from source

I'm trying to build Pygobject on Ubuntu 64-bit 16.04. I followed instructions give here https://python-gtk-3-tutorial.readthedocs.io/en/latest/install.html#installing-from-source and I believe that the documentation needs more details:

Some points of confusion for me were:

  1. The Pre-built packages section does not have any details on how to install pygobject. If possible can those be added?
  2. Installing from source section refers to 1 but does not specify which version to download. So I downloaded latest version. Then the instructions say

Once you have installed JHBuild successfully, download the latest configuration from [1]. Copy files with the suffix .modules to JHBuild’s module directory and the file sample-tarball.jhbuildrc to ~/.jhbuildrc.

But in the downloaded folder from [1] I could not find any .modules files. What exactly needs to be done here is not clear to me.

  1. I followed instructions given at https://developer.gnome.org/jhbuild/unstable/getting-started.html.en and they were successful. The jhbuild sanitycheck was also successful.

  2. After I run jhbuild build pygobject I get a whole bunch of errors. For e.g.:

`Checking if "C_IN in public headers (no arpa/nameser_compat.h needed)" 
compiles: NO
Checking if "arpa/nameser_compat.h needed for C_IN" compiles: NO

gio/meson.build:35:6: ERROR:  Problem encountered: Could not find 
required includes for ARPA C_IN

A full log can be found at 
/home/anshulvj/.cache/jhbuild/build/glib/meson-logs/meson-log.txt
*** Error during phase configure of glib: ########## Error running 
meson --prefix /home/anshulvj/jhbuild/install --libdir lib - 
Dlibmount=false --buildtype=debugoptimized -Dgtk_doc=false 
/home/anshulvj/jhbuild/checkout/glib *** [6/10]

[1] Rerun phase configure
[2] Ignore error and continue to build
[3] Give up on module
[4] Start shell
[5] Reload configuration
[6] Go to phase "wipe directory and start over"
choice: `

Doesn't matter what I choose, it either ends the build or gives errors like the following, if I choose [2]:

*** Building glib *** [6/10]
ninja  
ninja: error: loading 'build.ninja': No such file or directory
*** Error during phase build of glib: ########## Error running ninja   
*** [6/10]
.
.
.

and then

configure: error: Package requirements (glib-2.0 >= 2.57.1) were not met:

Requested 'glib-2.0 >= 2.57.1' but version of GLib is 2.48.2

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables GLIB_CFLAGS
and GLIB_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
*** Error during phase configure of gobject-introspection: ########## Error running /home/anshulvj/jhbuild/checkout/gobject-introspection/autogen.sh --prefix /home/anshulvj/jhbuild/install --disable-Werror --with-python=python3 --disable-static --disable-gtk-doc  *** [9/10]

Which is weird because I cannot find anything related to installing glib2.57 or greater online. (https://github.com/GNOME/glib)

The documentation at https://python-gtk-3-tutorial.readthedocs.io/en/latest/install.html does not deal with these errors and I'm completely lost. I googled a lot but did not find anyone who was facing the same issue. If this does not work I'm going to give up on Python3+GTK3+.

Any help/pointers are appreciated.

Give example of using a Gtk Stock Item (e.g. for a button)

I'm intending to use a Stock Item for a button. I found the tutorial by googling for "Gtk use stock item" and while I appreciate seeing the various icons, I'd love to see an example of how to actually use such a stock item, e.g. with a button.

I finally found the following to work:

        image = Gtk.Image()
        image.set_from_stock(Gtk.STOCK_ABOUT, Gtk.IconSize.BUTTON)
        self.button = Gtk.Button(
            #label='Hello',
            #stock=Gtk.STOCK_ABOUT,
            image=image,
            )

Another option might be to ignore the default settings (per http://stackoverflow.com/a/3175809/2015768):

        settings = Gtk.Settings.get_default()
        settings.props.gtk_button_images = True

        self.button = Gtk.Button(
            #label='Hello',
            stock=Gtk.STOCK_ABOUT,
            #image=image,
            )

Where can I find documentation for GtkSource

PyGObject website points the documentation link to pgi-docs which are basically pypy bindings.
I am looking for GTK+ python bindings documentation. Basically for things like :

from gi.repository import Gtk, GtkSource, GObject

I would also like to note that Porting PyGTK to PyGObject is not useful as there are lot of changes since then (pygtk uses gtk2) and there are things added to GtkSource in GTK+ -3 like GtkSourceCompletion which are not mentioned in pygtk sourceview documentation

Gtk.Builder example typo

The code included as the last example in section 19.3 "Connecting Signals" is:

.. literalinclude:: ../examples/builder_example.py
    :linenos:
    :lines: 3-12
from gi.repository import Gtk

class Handler:
    def onDeleteWindow(self, *args):
        Gtk.main_quit(*args)

    def onButtonPressed(self, button):
        print("Hello World!")

builder = Gtk.Builder()

The last line should be

builder.connect_signals(Handler())

which is line 14 of builder_example.py.

examples/label_example.py

It's not obvious why Alt + P works in that line

label = Gtk.Label.new_with_mnemonic(
            "_Press Alt + P to select button to the right")

I think it should be better changed to

label = Gtk.Label.new_with_mnemonic(
            "Press Alt + _P to select button to the right")

Object Properties Example Issues

Section 20.3.2:

Flags are GObject.PARAM_READABLE (only read access for external code), GObject.PARAM_WRITABLE (only write access), GObject.PARAM_READWRITE (public)

Should read:

Flags are GObject.ParamFlags.READABLE (only read access for external code), GObject.ParamFlags.WRITABLE (only write access), GObject.ParamFlags.READWRITE (public)

from gi.repository import GObject

class MyObject(GObject.GObject):

__gproperties__ = {
    "int-prop": (int, # type
                 "integer prop", # nick
                 "A property that contains an integer", # blurb
                 1, # min
                 5, # max
                 2, # default
                 GObject.PARAM_READWRITE # flags
                ),
}

def __init__(self):
    GObject.GObject.__init__(self)
    self.int_prop = 2

def do_get_property(self, prop):
    if prop.name == 'int-prop':
        return self.int_prop
    else:
        raise AttributeError, 'unknown property %s' % prop.name

def do_set_property(self, prop, value):
    if prop.name == 'int-prop':
        self.int_prop = value
    else:
        raise AttributeError, 'unknown property %s' % prop.name

I can't get this example to work at all, errors that I have found in python3:

  1. GObject.PARAM_READWRITE should be GObject.ParamFlags.READWRITE
  2. raise AttributeError, 'unknown..' should be raise AttributeError("unknown...") in python3
 myobject = MyObject()
 myobject.do_get_property(int_prop)
 NameError: name 'int_prop' is not defined
  1. No mention of how to create a GObject.ParamSpec using any of the methods

Conceptionally in unicode.txt

I think your mean "Conceptually" as the first word of the paragraph immediately following the "Definitions" heading. As far as I can tell, the word, "Conceptionally" does not exist.

The same word (Conceptionally) also appears in other places. So I guess a "Find and Replace" over all the text files is called for, if you agree to this suggestion.

Hope that helps.

Peter

Installation: build gtk+-3 with jhbuild

gtk+ has now branched and building gtk+ using jhbuild might build gtk+ master branch (which is gtk4).

So explicitly say to build gtk+-3: jhbuild build gtk+-3

Thanks.

Stock items are deprecated

The file chooser example uses stock items for the open / cancel button, although these are deprecated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.