-
1. What Is Pygtk?
PyGTK (a.k.a python-gtk or gtk-python) is a set of bindings to the GTK+ user interface toolkit for the Python language. The main site to look for more information on these bindings is . There, new releases, news, reference docs, tutorials, applications built on top of.
Python is an interpreted language with a very clean syntax, high-level data structures, dynamic typing, object oriented characteristics and generally acceptable performance.
GTK+ is a graphical user interface toolkit, which includes user interface components (hereafter called by the usual name widgets) and a framework for handling events that are produced upon these components.
A binding is code (usually a library) that allows you to access functions that were coded in another language. In our case, GTK+ was written in C, and applications written in C can use native GTK+. For a Python program to be able to create applications using the GTK+ framework, a special library has to be used. This library is PyGTK.
-
2. How Do I Get The Very Latest Pygtk Source Code [from Git]?
PyGTK is kept in gnome git; the module name for PyGTK is “pygtk”. The module name for gnome-python is “gnome-python”, so to check it out, type:
git clone git://git.gnome.org/pygtk
and possibly:
git clone git://git.gnome.org/gnome-python
git clone git://git.gnome.org/gnome-python-desktop
git clone git://git.gnome.org/gnome-python-extras
Please note that to use PyGTK you rely on recent code for GTK+ , GLib, atk, pango, Python. How recent exactly these dependencies need to be depends largely on the current target for the PyGTK development team. In general, CVS HEAD will use the latest CVS, but ask on the mailing list if problems arise.
Python Interview Questions
-
3. How Do I Extend Pygtk (or The Art Of Wrapping)?
In order to make a new wrapper for PyGObject/PyGTK, you can use this FAQ as a guideline or checklist. Don’t miss out FAQ 6.3 which has a link to an online article, additionally.
Let’s call the library “foo” (how original)
1) foo.defs.
- Use h2defs.py found in pyobject/codegen/ on all your _public_ headers for the library.
h2defs.py /usr/include/foo-1.0/*.h > foo.defs
2) foomodule.c
- Use atkmodule.c as a template. Replace all instances of atk with foo.
- You most probably won’t use any constants (since they require additional work), so just comment out pyatk_add_constants (m, “ATK_”);
3) foo.override
- You can also use atkmodule.c as a template for the override file.
- Remove the only function in there (atk_relation_new) and replace the atk headers with your own.
- Don’t forget to replace the modulename too.
4) Makefile.am
AUTOMAKE_OPTIONS=1.5
INCLUDES = $(PYTHON_INCLUDES) $(FOO_CFLAGS)
# foo module
pyexec_LTLIBRARIES = foomodule.la
foomodule_la_LDFLAGS = -module -avoid-version -export-symbols-regex initfoo
foomodule_la_LIBADD = $(FOO_LIBS)
foomodule_la_SOURCES = foomodule.c
nodist_foomodule_la_SOURCES = foo.c
foo.c: foo.defs foo.override
CLEANFILES = foo.c
EXTRA_DIST = foo.override
.defs.c:
(cd $(srcdir)
&& $(PYTHON) codegen/codegen.py
–override $*.override
–prefix py$* $*.defs) > gen-$*.c
&& cp gen-$*.c $*.c
&& rm -f gen-$*.c
—
Should be enough for you to get started
5) configure.in
- Copy pygobjects configure and remove unnecessary stuff. Should be trivial. Don’t forget to define a FOO_LIBS and FOO_CFLAGS
PKG_CHECK_MODULES(FOO, foo >= 1.2,,)
AC_SUBST(FOO_CFLAGS)
AC_SUBST(FOO_LIBS)
Finally, copy autogen.sh and hopefully you’ll have most functions wrapped.
Eventually you’ll have to wrap a few functions by hand, functions that the code generator cannot handle. Mostly functions with inout params (**) and GSList/GList parameters.
-
4. How Do I Compile Pygtk Or Gnome-python From Svn?
You need the GTK+ 2.x libraries, as you’d expect (see FAQ 21.2). There are three packages you want to build:
- gnome-python/pygtk
- gnome-python/pyorbit
- gnome-python/gnome-python
You should run
./autogen.sh
make
make install
in each of these, in that order. If you want to build from SVN, you might want to look at a build script. James recommends jhbuild (also in GNOME svn).
If you want to install them to a separate prefix, eg if you don’t have write access to /usr/local, use –prefix as an argument to autogen.sh or configure, eg:
./configure –prefix /home/user/prefix
And then, don’t forget to set PYTHONPATH before running the program, eg:
export PYTHONPATH=/home/user/prefix/lib/python2.3/site-packages
Then you can finally run your program.
Python Tutorial
-
5. How Do I Search Bugzilla For Pygtk Bugs?
You may then specify the version, OS and any other relevant information.
If I am trying to do a general query, it helps to “select all” in these boxes by clicking on the first entry and then shift clicking on the last entry. You may also want to activate all the ‘Status’ entries to see resolved bugs, etc.
Once you have configured all these parameters, go to the Text information section, enter your search terms in the Description or Summary boxes, and click ‘Submit Query’.
PHP Interview Questions
-
6. My Programs Configure Says: No Package ‘pygtk-2.0’ Found?
That’s because the configure script can’t find the installed version of pygtk-2.0.
If you build pygtk on your own, from source, then you need to write the following before running the configure script:
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
Or, replace /usr/local with the prefix you installed pygtk to. /usr/local is however the default and most commonly used one.
If you did not install it from source then it means that you forgot to install the devel/dev package. For Red Hat based distributions (Fedora, SuSe, Mandrake etc) you need to install pygtk2-devel and for debian based distributions you need to install pythonX.Y-gtk2-dev, where X.Y stands for the python version you’re using.
-
7. Is There A Pygtk For Macos X?
There are two ways of running PyGTK on OS X.
One way is running it with native support, which is still in early stages of development and is not feature complete yet. There are currently (as of June 2008) no available binaries for GTK+ running natively under OSX, so you need to compile GTK+ yourself. The instructions here tell you how to build GTK+, but not PyGTK; after following the steps here you also must do “jhbuild build meta-gtk-osx-python”.
The second way is using Apple’s X11 server, which is closer to other Unix systems for portability, but won’t integrate very well with the rest of the OS X desktop. If you are running Mac OS X 10.3 (Panther) or above X11 is available as an optional feature from the install CDs.
PHP Tutorial
Ruby on Rails Interview Questions
-
8. Does Pygtk Have Timers?
yes! The function you are looking for is gobject.timeout_add() (or gobject.timeout_add_seconds() for longer periods).
-
9. How Do I Install Pygtk-2 And Pygtk-0 Side By Side In The Same System?
It used to be that if you installed PyGTK-2 and PyGTK-0.x in a same version of Python, the applications that required PyGTK-0.x would stop working. This happened because Python would import PyGTK-2 preferentially, and the names of the modules are the same: ‘gtk’.
(There are three different ways detailed to solve this problem, but I will not recommend methods 2 and 3 unless you are unable to upgrade to a version that supports method 1).
• Method 1 (the “pygtk.pth” method)
(Note that RedHat 8.0 ships versions PRIOR to these, you will need to either upgrade the system packages, or use method 2 if you want to install PyGTK-0 and PyGTK-2 together on RH8.)
James has added to pygtk a mechanism that allows installation of both pygtk and pygtk2 to work side by side. This method should be transparent – you can install both versions and simply require one or the other for each program you need (the default being the one you install last), as per faq 2.4. It is implemented by using a pygtk.pth file that indicates which is the default (which one `import gtk’ uses) version.
Note that pygtk.pth only works if you use the *default python install path* – if you specify a –prefix to configure it will not work and you will *have to use method 2*!
You can install the two conflicting versions to a different prefix. When configuring pygtk2, use something like:
./configure –prefix=/usr/local/gtk2/
All pygtk2 files will be installed in this case to
/usr/local/gtk2/lib/pythonX.Y/site-packages/
With X.Y replaced by the major and minor numbers in your python version. You will then need to adjust PYTHONPATH (or sys.path) to look at the correct version for the program you want to run. If it requires pygtk2, you could use something like:
export PYTHONPATH=/usr/local/gtk2/lib/pythonX.Y/site-packages/:$PYTHONPATH
Ubuntu Certified Professional Interview Questions
-
10. If I Installed Pygtk-0 And Pygtk-2 In Parallel (using Pygtk.pth) How Do I Indicate Which One My Script Should Use?
The new versions of PyGTK provide a pygtk module in which you can call a method require() that allows you to request one version or the other:
pygtk.require(“1.2”) # for pygtk-0
and
pygtk.require(“2.0”) # for pygtk2
Note that you should do this before importing the gtk or gnome modules:
# To require 2.0
import pygtk
pygtk.require(“2.0”)
import gtk, gtk.glade, gnome, gnome.ui
or:
# To require 1.2
import pygtk
pygtk.require(“1.2”)
import gtk, libglade, gnome, gnome.ui
Ruby on Rails Tutorial
-
11. Which Versions Of Pygtk Support Parallel Install Using The Pygtk.pth Method?
James Henstridge and Johan Dahlin implemented parallel install support in versions:
– pygtk-0.6.10
– gnome-python-1.4.3
– pygtk2-1.99.13
So any version equal to or later than that is fine. Note that 0.6.10 and 1.4.3 had bugs in it, and you should upgrade to 0.6.11 and 1.4.4 if possible.
Django Interview Questions
-
12. For Some Users Import Libglade (or Gdk) Is Working And For Some Users It’s Not?
It’s possible that at the top of your script you have #!/usr/bin/env python as the script interpreter line. This searches the path for python, instead of hardcoding it to particular place, which is useful. However, some systems have been found with multiple versions of Python, one of which works with GTK1 and one of which only works with GTK2.
Figure out which one is working for your users, and change their script interpreter or path to use that one.
Python Interview Questions
-
13. How Do I Get My 1.2 Gladefiles To Work With 2.0?
There is a program included with libglade 2.0.x called libglade-convert that will do a pretty good job at converting the interface file to the new format. You should be able to edit the file in glade 1.1 after that.
Dave notes that you will probably have to redo all your dialog boxes, since they are going to be converted without some of the GTK 2 things, such as the correct active area interface and GTK 2 button images. You’ll also have to redo your trees and lists to conform with GTK 2. A moderately sized project will take around 8 hours to do this to. Even if you don’t “make install” libglade 2.0.x, you can use the Python file included (but renamed) in the distribution.
Django Tutorial
-
14. When I Connect To A Signal, My Handler Gets Called But Reports “xxx Takes No Arguments (1 Given)”?
Signal callbacks have specific signatures. This means that when a signal is emitted, it will send to the callback function a number of parameters. The first parameter is the widget which generated the event, and the rest vary depending on what signal is being emitted.
To handle a callback, your function signature, therefore, must take this into account. Often you don’t even want to use any of the arguments, just trigger an action on a certain signal; an easy way to do this is using a variable argument list (*args) and ignoring them in your method:
def on_win_delete(*args):
print “Deleted, and who cares why”
w = gtk.Window()
w.connect(“delete-event”, on_win_delete)
If you are attaching to a method, be sure to provide the usual self in the method definition, and specifying self.on_foo_signal as the function to attach to.
-
15. How Do I Detect That A Mouse Or Keyboard Event Has Been Triggered?
The correct way is to hook to some of the basic event signals and then act upon receiving them. The signals you want to look for are:
- mouse motion
- key presses
- button presses
However, many widgets don’t have their event masks properly set, so they will ignore these events. The following example shows how it should be done for a GtkWindow, adding the necessary event masks, and then hooking to the signals. Note that you would have to alter the wakeup function to handle the timer operations you would need for a screensaver.
def wakeup(widget, event):
print “Event number %d woke me up” % event.type
w = gtk.Window()
w.add_events(gtk.gdk.KEY_PRESS_MASK |
gtk.gdk.POINTER_MOTION_MASK |
gtk.gdk.BUTTON_PRESS_MASK |
gtk.gdk.SCROLL_MASK)
w.connect(“motion-notify-event”, wakeup)
w.connect(“key-press-event”, wakeup)
w.connect(“button-press-event”, wakeup)
w.connect(“scroll-event”, wakeup)
w.show()
gtk.main()
Note that mouse “scroll-wheel” events are implemented as button clicks in the Xorg X11R6 server (button 4 for scroll up, button 5 for scroll down).
GNU Image Manipulation Program(GIMP) Interview Questions
-
16. I’ve Fiddled With The Mask But Nothing Happened. Why?
One common error is to confuse gdk event TYPEs with MASKs. The type number indicates precisely which gdk event was generated, but it is not directly related to the event mask:
yeah. A number of the masks cover multiple events and some events are selected by different masks
All event mask constants end with _MASK, and that is a good rule to remember. When doing add_events, you do NOT want (see, no _MASK!):
widget.add_events(gtk.gdk.MOTION_NOTIFY | gtk.gdk.BUTTON_PRESS)
This is the correct command:
widget.add_events(gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK)
(This example is particularly tricky because using BUTTON_PRESS will actually enable the pointer motion mask; this happens because the of the numeric constants used. Remember _MASK.)
TurboGears Tutorial
-
17. Which Widgets Are Unable To Receive Events Or Be Styled?
certain widgets didn’t have associated X windows, and for that reason were unable to handle events or be styled and coloured. These widgets are (add a Gtk in front if they look unfamiliar):
Alignment
AspectFrame
Arrow
Bin
HBox
VBox
Frame
Image
Label
Pixmap
ScrolledWindow
HSeparator
VSeparator
Table
TurboGears Interview Questions
-
18. I Attach A Callback To A Signal, But I Keep Getting An Error: “typeerror: Object Of Type X Is Not Callable”?
When connecting an event handler, you must provide the function name. A common mistake is to pass a call instead of the name. In other words, you should not add parenthesis after the function name.
#
# WRONG
button = gtk.Button(label=”Quit”)
button.connect(“clicked”, gtk.main_quit())
As you can see, gtk.main_quit() is a call, not the function name. The correct way to do it would be:
# RIGHT
button = gtk.Button(label=”Quit”)
button.connect(“clicked”, gtk.main_quit)
Always remember to use gtk.main_quit() instead of gtk.mainquit() since the last one is deprecated.
PHP Interview Questions
-
19. I Want My Callback To Execute, But Not The Default Callback (or, How To I Stop Gtk From Doing The Default Action When Doing X)?
Many times, you are customizing behaviour of a widget, or changing a policy in GTK, and the default action it does it not what you want. To get around this, we rely on a fundamental point in GTK: that GTK, as well as applications, mainly uses signals to get things done in the interface.
The process to disable a default action is:
- Find out what signal is being emitted and handled by the default handler. Many times you already know the signal since you may be hooking to it already, and observing the default action happen after yours.
- call widget.emit_stop_by_name(“signal_name”) (to stop the signal emission in the current widget)
- return True (to make sure that the signal won’t propagate into parent handlers that may be the actual culprits for the default action)
An example of this usage was reported by Graham Ashton. He had customized a keypress handler for a window, but every time the user triggered the Alt-arrow combination he was handling, the focus moved around between the widgets in the interface (as is the default behaviour).
The solution was simply calling window.emit_stop_by_name(“key_press_event”) and returning True.
Lisp programming Tutorial
-
20. When Creating A New Signal, How Do I Define One Of The Signal Arguments As Python Data?
When you add your signal using gobject.signal_new(), use gobject.TYPE_PYOBJECT as the type for the argument being passed in:
gobject.signal_new(“signal”, ClassName,
gobject.SIGNAL_RUN_LAST,
gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT,))
And then you can emit the signal with Python objects:
mydict = {}
mydict[“foo”] = “bar”
class_instance.emit(“signal”, mydict)
And get them when you connect on the other side:
def signal_cb(instance, mydict):
print mydict[“foo”]
class_instance.connect(“signal”, signal_cb)
Lisp programming Interview Questions
-
21. How Do I Specify User Data To A Signal?
widget.connect(“my_signal”, handler, userdata [, …])
As you can see, you can pass as many items as userdata; the function will receive the same number of user data arguments.
-
22. Why Does Handling Expose Events Break Drag-n-drop?
If you are calling
queue_draw_area(x_beg, y_beg, x_end, y_end)
in your expose_event handler, don’t. It seems to break event propagation which causes drag and drop to not work any more.
wxPython Tutorial
-
23. How Do I Pass Extra Data To A Signal Handler?
The signal connection methods connect() and connect_after() take an optional third parameter that can be used to supply extra data to a signal handler callback. Any Python object can be passed so you can use a list, tuple or dictionary if you want to pass multiple extra values. Since the signal handler function will receive the widget that emitted the signal as its first parameter, often it’s convenient to pass a second related widget as the extra data.
Suppose you have a dialog with an entry widget. If you want the dialog response handler to do something with the entry value, you could connect to the response signal like this
dialog.connect(‘response’, on_dialog_response, entry)
This lets you easily access methods of the entry widget in the signal handler, perhaps to get the text in the entry
def on_dialog_response(widget, response, entry):
if response == gtk.RESPONSE.ACCEPT:
print ‘Accepting’, entry.get_text()
Something that might trip you up especially if you are new to Python programming is that you probably don’t want to try to pass the entry text to the signal handler like this
# probably wrong!
dialog.connect(‘response’, on_dialog_response, entry.get_text())
The get_text() method is executed when the signal is connected so this would pass a constant value as the extra data. Usually you will want the signal handler to see the current state of the entry widget.
wxPython Interview Questions
-
24. How To Construct My Own “fake” Gtk.gdk.event?
It’s very easy. Let’s go create a keypress event that is the same as if the user has pressed Ctrl+Enter:
event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
event.keyval = gtk.keysyms.Return
event.state = gtk.gdk.CONTROL_MASK
event.time = 0 # assign current time
widget_that_should_accept_signal.emit(‘key_press_event’, event)
the last line “passes” the signal to the widget we want to handle this fake event.
Ruby on Rails Interview Questions
-
25. How Do I Pass Data To A Signal Handler In Glade?
In theory, you should fill in the Object column when specifying a callback to connect to the signal. In GtkBuilder mode, you may only specify objects that Glade knows about. This is sufficient for implementing such things as the encapsulation pattern demonstrated elsewhere in iit, used to provide a callback everything it needs to function in, for example, a cell renderer callback, by passing the TreeModel as user data.
In practice, don’t even try. Pygtk 2 and Glade are both too buggy to attempt this. Manually connect any signals that need user data.
-
26. How Do I Change Font Properties On Gtk.labels And Other Widgets?
label = gtk.Label(“MyLabel”)
label.modify_font(pango.FontDescription(“sans 48”))
This method applies to all widgets that use text, so you can change the text of gtk.Entry and other widgets in the same manner.
Note that, some widgets are only containers for others, like gtk.Button. For those you’d have to get the child widget. For a gtk.Button do this:
if button.get_use_stock():
label = button.child.get_children()[1]
elif isinstance(button.child, gtk.Label):
label = button.child
else:
raise ValueError(“button does not have a label”)
Basic C Interview Questions
-
27. Why Don’t My Style Changes Apply Only To The Widget I Requested It From?
Ricardo Lenzi writes:
get_style() returns an object what aways have the current style of widget. If you want to save an static style, use get_style().copy() instead:
style = widget.get_style().copy()
This has some pretty odd effects. If you are creating a window with many gtk.Label’s, for instance, and you alter the actual style object (not a copy() if it), all widgets will eventually change style (when they are redrawn by GTK+).
Ubuntu Certified Professional Interview Questions
-
28. How Do I Use The Style Object?
Each widget has an associates style object that can be manipulted. The basic method is get_style(), which returns a GtkStyle object, and the associated set_style(style_object).
The style is shared between widgets of the same type (XXX: is this true?). To change the style of only one widget in your application, the style object offers a copy() method, which returns a new copy of the GdkStyle, which can me changed and set_style() back to the desired widget.
All attributes of a style can be get and set independently by direct access. The most important attributes of style are the colours (see faq 4.6):
- fg
- bg
- light
- dark
- mid
- text
- base
- black
- white
And the font and bg_pixmap attributes.
-
29. How Do I Change The Colour Of A Widget (or How Do I Get A Gdkcolor)?
There is some confusion about GdkColor and how it is created. There are both the GdkColor() class and colour_alloc() that seem to do the right thing, but they are both duds (as far as I can tell).
The right way of creating a colour is getting the colormap from the widget and using it to allocate a new colour using the GtkColorMap’s alloc method:
e = gtk.Entry()
map = e.get_colormap()
colour = map.alloc_color(“red”) # light red
This way you end up with a red GdkColor in the variable colour. Apart from the X11 rgb.txt names, you can also use hex triplets:
colour = map.alloc_color(“#FF9999”) # light red
The next step is understanding how to manipulate GtkStyle’s colour attributes, which are actually dictionaries: each attribute maps a number of different gtk constants that indicate states:
- gtk.STATE_NORMAL, the normal state of the widget.
- gtk.STATE_ACTIVE, a clicked button or checkbutton, etc.
- gtk.STATE_INSENSITIVE, when the widget is insensitive (set_sensitive(0))
- gtk.STATE_PRELIGHT, when onmouseovered
- gtk.STATE_SELECTED, when part of the widget is selected (text in a GtkEntry, or a selected radiobutton)
So, to change the default border of our entry above to red:
style = e.get_style().copy()
style.bg[gtk.STATE_NORMAL] = colour
e.set_style(style)
Final hint: the default colour for a GtkEntry background is gray84.
Python Automation Testing Interview Questions
-
30. How Do I Get A Graphics Context, Or Gdkgc?
Use the new_gc() method of GdkWindow (not GtkWindow, notice):
gdkwin = widget.window
gc = gdkwin.new_gc()
-
31. How Does The Alloc() Method To The Gdkcolormap Work?
gdk.Colormap.alloc_color can take a number of formats:
cmap = widget.get_colormap()
color = cmap.alloc_color(“#FFCCAA”)
color = cmap.alloc_color(“red”)
color = cmap.alloc_color(0, 0, 65535)
Note that the third format uses a tuple to specify the individual values for Red, Green and Blue (RGB), each item being an integer from 0 to 65535 (corresponding, therefore, to 0x0-0xFF).
-
32. How Do I Use Pango Instead Of Gdkfont For Font Handling In A Gtkdrawingarea?
Create a font description with pango. You will then need a pango layout for the text you want to display. You have to tell the layout which font description to use and draw it with the draw_layout() method instead of the draw_text() method.
import pango
# create a font description
font_desc = pango.FontDescription(‘Serif 12’)
# create a layout for your drawing area
layout = darea.create_pango_layout(‘hello pango!’)
# tell the layout which font description to use
layout.set_font_description(font_desc)
# draw the text with the draw_layout method
darea.window.draw_layout(gc, x, y, layout)
You can find out about the size of the text by using the get_pixel_size() method from your pango layout object. e.g.:
# get the pixel size of a layout
text_width, text_height = layout.get_pixel_size()
-
33. How Do I Get Antialiased Fonts In Gtk+?
The original core font rendering engine in XFree86 didn’t support AA fonts. However, for GTK+ 2.0 onwards, the Xft font rendering backend can be used to render antialiased fonts. To select it using GTK+2.0, use:
export GDK_USE_XFT=1
It’s on by default on 2.2 onwards, and in 2.4 the core engine is no longer used by GTK+.
Note that the Xft backend is much better at producing scaled versions of the fonts. The reason is that the core X font system, when you use scalable fonts, will render the entire set of glyphs as bitmaps at the requested size when you open the font (which isn’t fast or a good use of memory — it quite large for big point sizes or fonts with large coverage, such as with Asian fonts).
Django Interview Questions
-
34. Does Pygtk Support Truetype Fonts?
If your X server does, the answer is yes. X requires the freetype module be loaded to be able to handle TTF fonts, but all post-4.0 servers include the module by default.
-
35. What Units Does Pango Use To Define Sizes And Widths?
Pango uses a constant called pango.SCALE to convert between pixels and pango’s native unit. You can use pango.PIXELS() to convert from the native unit back to pixels, or just divide.
-
36. Can I Find Out How Long (wide) A String Is In A Certain Font?
In PyGTK2, you can use pango calls to find out how wide a string will be, using the pango context of the widget that contains (or that will contain) your text:
context = widget.get_pango_context()
metrics = context.get_metrics(‘font name, 12’)
width = pango.PIXELS(metrics.get_approximate_char_width() * n_chars)
For a monospaced font, this should be quite accurate. You can then use widget.set_size_request() if you would like to set that width as the minimum width for the widget/view.
In PyGTK-0.6, you can ask the font directly how long a given string is going to be, as well as how high. Retrieve the font object from the style, and then query it with the string in question:
font = widget.get_style().font
h = font.height(my_string)
w = font.width(my_string)
The methods return pixel counts. You can then set the size manually to any function of those parameters. For instance, to make a widget twice as wide and as high as the string you measured with, use:
widget.set_usize(w*2, h*2)
GNU Image Manipulation Program(GIMP) Interview Questions
-
37. Why Does Fontselection’s Set_font_name Return False?
It needs to be added to a window before the font lists are populated.
>>> w = gtk.Window()
>>> f = gtk.FontSelection()
>>> f.get_font_name()
‘Sans 10’
>>> f.set_font_name(‘Sans 12’)
False
>>> w.add(f)
>>> f.set_font_name(‘Sans 12’)
True
Once added to the window, the result will indeed be True.
-
38. Can I Pass Strings Of Unicode Instance To Gtk Or Do I Need To Convert Them To Utf8?
No you don’t have do manually convert your strings in utf8. PyGTK will do this for you.
label.set_text(u’abc’)
So the above is indeed valid and not only to labels but to any widget.
-
39. How Do I Check If A Widget Is Currently Sensitive?
In pygtk, you get properties by calling the get_property() method:
if widget.get_property(‘sensitive’) == 0:
print “I’m insensitive!”
Note:
In ancient versions of pygtk (0.6.x) you could access them using a dictionary interface, this was removed in the 2.x series.
More recently (since PyGTK 2.8) the following method can be used:
if not widget.props.sensitive:
print “I’m insensitive!”
-
40. Where Is Get_state() In Pygtk 0.6.x?
James Henstridge points out that there is no get_state() function in gtk 1.2.
And therefore no way to wrap it in pygtk. There are actually a number of state constants defined in gtk:
gtk.STATE_ACTIVE
gtk.STATE_NORMAL
gtk.STATE_SELECTED
gtk.STATE_INSENSITIVE
gtk.STATE_PRELIGHT
but they are to be used with set_state(). In pygtk2, get_state() is implemented and wrapped.
TurboGears Interview Questions