sebp / pygobject-tutorial Goto Github PK
View Code? Open in Web Editor NEWTutorial for using GTK+ 3 in Python
Home Page: https://python-gtk-3-tutorial.readthedocs.io/
License: GNU Lesser General Public License v2.1
Tutorial for using GTK+ 3 in Python
Home Page: https://python-gtk-3-tutorial.readthedocs.io/
License: GNU Lesser General Public License v2.1
How to:
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>
In section 15.2.1, get_text requires three arguments to work: start_iter, end_iter, and include_hidden_chars (which in PyGtk was implicitly true.)
Chapter 16 about menus uses the UIManger which is deprecated since GTK 3.10. I was looking at how to update the example, but I haven't come up with a solution yet.
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?
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.
I propose splitting the tutorial in two parts:
PyGObject documentation, describing the gi API (require_version etc.), GObject, Porting from old static bindings, properties, signals, threading, string handling
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 properly due to deprecated function override_background_color
I like to submit a pull request for the code ..
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...
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'
I tried to investigate the GtkApplication
API documentation but I still have no idea where this method should be.
Hello.
https://github.com/sebp/PyGObject-Tutorial
says
Tutorial for using GTK+ 3 in Python http://live.gnome.org/PyGObject
But, http://live.gnome.org/PyGObject redirected to
https://wiki.gnome.org/action/show/Projects/PyGObject?action=show&redirect=PyGObject
and that page says
https://pygobject.readthedocs.io
I'm confused.
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)
.
Hi, I found the wrong description about Gtk.IconView.set_cursor() method as follow:
If cell is None
, then focus is given to the cel specified by it.
=>
If cell is not None
, then focus is given to the cel specified by it.
I refered and quoted from GTK+ reference manual[1] for above description.
[1] http://developer.gnome.org/gtk/stable/GtkIconView.html#gtk-icon-view-set-cursor
Thank you.
Takeshi.
How I will change the cursor shape and color of multi-line textarea?
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.
Please add a section about porting from pygtk.
One of the most favorite errors is this:
TypeError: pack_start() takes exactly 5 argument(s) (2 given)
Thank you.
I read
https://python-gtk-3-tutorial.readthedocs.io/en/latest/
and I guess
https://python-gtk-3-tutorial.readthedocs.io/ko/latest/
shows Korean translation of the tutorial.
But not.
How can make Korean translation and into the ko directory ?
One of the main tools to debug/explore a gtk interface nowadays is the inspector.
We should add a page which presents what it can do, for what it is useful for and how to enable it.
I've tried to write something up on GTK+ and threads: http://www.student.tugraz.at/christoph.reiter/pygobject-threading/
Would this be considered for inclusion?
At http://python-gtk-3-tutorial.readthedocs.org/en/latest/introduction.html, section 2.1, the prose text doesn't match up with the code lines shown. Also, the code snippet after "The next line creates an empty window." is empty.
https://python-gtk-3-tutorial.readthedocs.io/en/latest/entry.html example shows big empty gap from line 61 to 77. Thanks.
best regards,
faraco
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:
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!
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).
It looks like the font name for Inconsolata
has been mispelled: i was wondering for some time why my browser didn't like it, then i've seen it's written "Incosolata"...
It looks like that the currently suggested way to create MenuBars and ToolBars is deprecated?
python-gtk-3-tutorial.readthedocs.io/en/latest/menus.html
https://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Action.html#Gtk.Action
How can a new user know how to solve this now? I can not find any example code using the new solution.
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").
The Drag and drop tutorial refers to Gdk.DestDefaults and should be Gtk.DestDefaults
https://github.com/sebp/PyGObject-Tutorial/blob/master/source/drag_and_drop.txt#L64
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.
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...
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.
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
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()
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:
pygobject
. If possible can those be added?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.
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.
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.
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,
)
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
gsettings is an integrate part of GTK application. I'd like to see a best practice on how to use gsettings with GTK.
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.
There is no documentation for Gtk.SearchEntry
.
http://lazka.github.io/pgi-docs/index.html#Gtk-3.0/classes/SearchEntry.html#Gtk.SearchEntry
At https://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html , the "Show on Github" link is broken.
GNOME apps are encouraged to use an ApplicationMenu rather than a Gtk.MenuBar. It would be great to add an example.
Hi,
I've started working on the generated API docs again (http://lazka.github.io/pgi-docs/) and would like to ask if the following change would be accepted:
If yes, I'll provide a patch/pull request.
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")
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:
myobject = MyObject()
myobject.do_get_property(int_prop)
NameError: name 'int_prop' is not defined
According to
https://developer.gnome.org/gtk3/stable/GtkAction.html
Warning
gtk_action_new has been deprecated since version 3.10 and should not be used in newly-written code. Use GAction instead, associating it to a widget with GtkActionable or creating a GtkMenu with gtk_menu_new_from_model()
The tutorial still recommends GtkAction.
There is no documentation for Gtk.InfoBar
.
Edit: Fixed wrong link.
https://developer.gnome.org/gtk3/stable/GtkInfoBar.html
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
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.
The file chooser example uses stock items for the open / cancel button, although these are deprecated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.