PyGTK FAQ Widgets

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(исправил название категории)
(Удалено по требованию автора...)
 
Строка 1: Строка 1:
-
In this part of the PyGTK programming tutorial, we will introduce some PyGTK widgets. Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar. The PyGTK toolkit's philosophy is to keep the number of widgets at a minimum level. More specialized widgets are  created as custom PyGTK widgets. 
 
-
== Label ==
 
-
The <b>Label</b> widget displays a limited amount of read-only text.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the Label widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
lyrics = """Meet you downstairs in the bar and heard
 
-
your rolled up sleeves and your skull t-shirt
 
-
You say why did you do it with him today?
 
-
and sniff me out like I was Tanqueray
 
-
 
-
cause you're my fella, my guy
 
-
hand me your stella and fly
 
-
by the time I'm out the door
 
-
you tear men down like Roger Moore
 
-
 
-
I cheated myself
 
-
like I knew I would
 
-
I told ya, I was trouble
 
-
you know that I'm no good"""
 
-
 
-
 
-
class PyApp(gtk.Window):
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
       
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
        self.set_border_width(8)
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.set_title("You know I'm no Good")
 
-
       
 
-
        label = gtk.Label(lyrics)
 
-
        self.add(label)
 
-
        self.show_all()
 
-
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
The code example shows some lyrics on the window.
 
-
 
-
<source lang="python">
 
-
lyrics = """Meet you downstairs in the bar and heard
 
-
your rolled up sleeves and your skull t-shirt
 
-
..."""
 
-
</source>
 
-
 
-
This is the text that we display.
 
-
 
-
<source lang="python">
 
-
self.set_border_width(8)
 
-
</source>
 
-
 
-
The <b>Label</b> is surrounded by some empty space.
 
-
 
-
<source lang="python">
 
-
label = gtk.Label(lyrics)
 
-
self.add(label)
 
-
</source>
 
-
 
-
The <b>Label</b> widget is created and added to the window.
 
-
 
-
[[image: pygtk_faq_lyrics.png | center]]
 
-
 
-
 
-
== CheckButton ==
 
-
<b>CheckButton</b> is a widget, that has two states. On and Off. The On state is visualised by a check mark. It is used to denote some boolean property.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the CheckButton widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
        self.set_title("Check Button")
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
        self.set_default_size(250, 200)
 
-
 
-
        fixed = gtk.Fixed()
 
-
        button = gtk.CheckButton("Show title")
 
-
        button.set_active(True)
 
-
        button.unset_flags(gtk.CAN_FOCUS)
 
-
        button.connect("clicked", self.on_clicked)
 
-
 
-
        fixed.put(button, 50, 50)
 
-
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.add(fixed)
 
-
        self.show_all()
 
-
 
-
    def on_clicked(self, widget):
 
-
        if widget.get_active():
 
-
            self.set_title("Check Button")
 
-
        else:
 
-
          self.set_title("")
 
-
       
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
We will display a title in the titlebar of the window, depending on the state of the <b>CheckButton</b>.
 
-
 
-
<source lang="python">
 
-
button = gtk.CheckButton("Show title")
 
-
</source>
 
-
 
-
<b>CheckButton</b> widget is created.
 
-
 
-
<source lang="python">
 
-
button.set_active(True)
 
-
</source>
 
-
 
-
The title is visible by default, so we check the check button by default.
 
-
 
-
<source lang="python">
 
-
if widget.get_active():
 
-
    self.set_title("Check Button")
 
-
else:
 
-
    self.set_title("")
 
-
</source>
 
-
 
-
If the <b>CheckButton</b> is checked we show the title. Otherwise we put empty text in the titlebar.
 
-
 
-
[[image: pygtk_faq_checkbutton.png | center]]
 
-
 
-
== ComboBox ==
 
-
<b>ComboBox</b> is a widget that allows the user to choose from a list of options.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the ComboBox widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
       
 
-
        self.set_title("ComboBox")
 
-
        self.set_default_size(250, 200)
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
 
-
        cb = gtk.combo_box_new_text()
 
-
        cb.connect("changed", self.on_changed)
 
-
 
-
        cb.append_text('Ubuntu')
 
-
        cb.append_text('Mandriva')
 
-
        cb.append_text('Redhat')
 
-
        cb.append_text('Gentoo')
 
-
        cb.append_text('Mint')
 
-
       
 
-
        fixed = gtk.Fixed()
 
-
        fixed.put(cb, 50, 30)
 
-
        self.label = gtk.Label("-")
 
-
        fixed.put(self.label, 50, 140)
 
-
        self.add(fixed)
 
-
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.show_all()
 
-
 
-
 
-
    def on_changed(self, widget):
 
-
        self.label.set_label(widget.get_active_text())
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
The example shows a combo box and a label. The combo box has a list of six options.
 
-
These are the names of Linux Distros. The label widget shows the selected option from the combo box.
 
-
 
-
<source lang="python">
 
-
 
-
cb = gtk.combo_box_new_text()
 
-
</source>
 
-
 
-
The <b>gtk.combo_box_new_text()</b> function is a convenience function that  constructs a new text combo box. It is a <b>ComboBox</b> just displaying strings.
 
-
 
-
<source lang="python">
 
-
cb.append_text('Ubuntu')
 
-
cb.append_text('Mandriva')
 
-
cb.append_text('Redhat')
 
-
cb.append_text('Gentoo')
 
-
cb.append_text('Mint')
 
-
 
-
</source>
 
-
 
-
The <b>ComboBox</b> is filled with textual data.
 
-
 
-
<source lang="python">
 
-
self.label.set_label(widget.get_active_text())
 
-
</source>
 
-
 
-
Inside the <b>on_changed()</b> method, we get the selected text out of the combo box and set it to the label.
 
-
 
-
[[image: pygtk_faq_combobox.png | center]]
 
-
 
-
== Image ==
 
-
The next example introduces the <b>Image</b> widget. This widget displays pictures.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the Image widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
       
 
-
        self.set_title("Red Rock")
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
        self.set_border_width(2)
 
-
 
-
        image = gtk.Image()
 
-
        image.set_from_file("redrock.png")
 
-
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.add(image)
 
-
        self.show_all()
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
We show the Red Rock castle in the window.
 
-
 
-
<source lang="python">
 
-
image = gtk.Image()
 
-
</source>
 
-
 
-
<b>Image</b> widget is created.
 
-
 
-
<source lang="python">
 
-
image.set_from_file("redrock.png")
 
-
</source>
 
-
 
-
We set a png image to the <b>Image</b> widget. The picture is loaded from the file on the disk.
 
-
 
-
[[image: pygtk_faq_redrock.jpg | center]]
 
-
 
-
In this chapter, we showed the first pack of basic widgets of the PyGTK programming library.
 
-
 
-
== Entry ==
 
-
The <b>Entry</b> is a single line text entry field.  This widget is used to enter textual data.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the Entry widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
       
 
-
        self.set_title("Entry")
 
-
        self.set_size_request(250, 200)
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
 
-
        fixed = gtk.Fixed()
 
-
 
-
        self.label = gtk.Label("...")
 
-
        fixed.put(self.label, 60, 40)
 
-
 
-
        entry = gtk.Entry()
 
-
        entry.add_events(gtk.gdk.KEY_RELEASE_MASK)
 
-
        fixed.put(entry, 60, 100)
 
-
 
-
        entry.connect("key-release-event", self.on_key_release)
 
-
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.add(fixed)
 
-
        self.show_all()
 
-
 
-
    def on_key_release(self, widget, event):
 
-
        self.label.set_text(widget.get_text())
 
-
       
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
This example shows an entry widget and a label. The text that we key in the  entry is displayed immediately in the label control.
 
-
 
-
<source lang="python">
 
-
entry = gtk.Entry()
 
-
</source>
 
-
 
-
<b>Entry</b> widget is created.
 
-
 
-
<source lang="python">
 
-
entry.connect("key-release-event", self.on_key_release)
 
-
</source>
 
-
 
-
If the text in the <b>Entry</b> widget is changed, we call the <b>on_key_release()</b> method.
 
-
 
-
<source lang="python">
 
-
def on_key_release(self, widget, event):
 
-
    self.label.set_text(widget.get_text())
 
-
</source>
 
-
 
-
We get the text from the <b>Entry</b> widget and set it to the label.
 
-
 
-
[[image: pygtk_faq_entry.png | center]]
 
-
 
-
== HScale ==
 
-
The <b>HScale</b> is It is a horizontal slider, that lets the user graphically select a value  by sliding a knob within a bounded interval.  Our example will show a volume control.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the HScale widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
import sys
 
-
 
-
class PyApp(gtk.Window):
 
-
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
 
-
        self.set_title("Scale")
 
-
        self.set_size_request(260, 150)
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
 
-
        scale = gtk.HScale()
 
-
        scale.set_range(0, 100)
 
-
        scale.set_increments(1, 10)
 
-
        scale.set_digits(0)
 
-
        scale.set_size_request(160, 35)
 
-
        scale.connect("value-changed", self.on_changed)
 
-
 
-
        self.load_pixbufs()
 
-
       
 
-
        self.image = gtk.Image()
 
-
        self.image.set_from_pixbuf(self.mutp)
 
-
 
-
        fix = gtk.Fixed()
 
-
        fix.put(scale, 20, 40)
 
-
        fix.put(self.image, 219, 50)
 
-
 
-
        self.add(fix)
 
-
 
-
        self.connect("destroy", lambda w: gtk.main_quit())
 
-
        self.show_all()
 
-
       
 
-
    def load_pixbufs(self):
 
-
   
 
-
        try:
 
-
            self.mutp = gtk.gdk.pixbuf_new_from_file("mute.png")
 
-
            self.minp = gtk.gdk.pixbuf_new_from_file("min.png")
 
-
            self.medp = gtk.gdk.pixbuf_new_from_file("med.png")
 
-
            self.maxp = gtk.gdk.pixbuf_new_from_file("max.png")
 
-
           
 
-
        except Exception, e:
 
-
            print "Error reading Pixbufs"
 
-
            print e.message
 
-
            sys.exit(1)
 
-
 
-
 
-
    def on_changed(self, widget):
 
-
        val = widget.get_value()
 
-
 
-
        if val == 0:
 
-
            self.image.set_from_pixbuf(self.mutp)
 
-
        elif val > 0 and val <= 30:
 
-
            self.image.set_from_pixbuf(self.minp)
 
-
        elif val > 30 and val < 80:
 
-
            self.image.set_from_pixbuf(self.medp)
 
-
        else:
 
-
            self.image.set_from_pixbuf(self.maxp)
 
-
               
 
-
       
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
In the example above, we have  <b>HScale</b> and  <b>Image</b> widgets. By dragging the scale we change the image on the <b>Image</b> widget.
 
-
 
-
<source lang="python">
 
-
scale = gtk.HScale()
 
-
</source>
 
-
 
-
<b>HScale</b> widget is created.
 
-
 
-
<source lang="python">
 
-
scale.set_range(0, 100)
 
-
</source>
 
-
 
-
We set the lower and upper boundaries of the scale.
 
-
 
-
<source lang="python">
 
-
scale.set_increments(1, 10)
 
-
</source>
 
-
 
-
The <b>set_increments()</b> method sets the step and page sizes for the range.
 
-
 
-
<source lang="python">
 
-
 
-
scale.set_digits(0)
 
-
</source>
 
-
 
-
We want to have integer values on the scale, so we set the number of decimal places to zero.
 
-
 
-
<source lang="python">
 
-
if val == 0:
 
-
    self.image.set_from_pixbuf(self.mutp)
 
-
elif val > 0 and val <= 30:
 
-
    self.image.set_from_pixbuf(self.minp)
 
-
elif val > 30 and val < 80:
 
-
    self.image.set_from_pixbuf(self.medp)
 
-
else:
 
-
    self.image.set_from_pixbuf(self.maxp)
 
-
</source>
 
-
 
-
Depending on the obtained value, we change the picture in the image widget.
 
-
 
-
[[image: pygtk_faq_scale.png | center]]
 
-
 
-
== ToggleButton ==
 
-
<b>ToggleButton</b> is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the ToggleButton widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
 
-
        self.color = [0, 0, 0]
 
-
       
 
-
        self.set_title("ToggleButtons")
 
-
        self.resize(350, 240)
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
        self.connect("destroy", gtk.main_quit)
 
-
 
-
        red = gtk.ToggleButton("Red")
 
-
        red.set_size_request(80, 35)
 
-
        red.connect("clicked", self.onred)
 
-
        green = gtk.ToggleButton("Green")
 
-
        green.set_size_request(80, 35)
 
-
        green.connect("clicked", self.ongreen)
 
-
        blue = gtk.ToggleButton("Blue")
 
-
        blue.set_size_request(80, 35)
 
-
        blue.connect("clicked", self.onblue)
 
-
 
-
        self.darea = gtk.DrawingArea()
 
-
        self.darea.set_size_request(150, 150)
 
-
        self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("black"))
 
-
 
-
        fixed = gtk.Fixed()
 
-
        fixed.put(red, 30, 30)
 
-
        fixed.put(green, 30, 80)
 
-
        fixed.put(blue, 30, 130)
 
-
        fixed.put(self.darea, 150, 30)
 
-
 
-
        self.add(fixed)
 
-
 
-
        self.show_all()
 
-
 
-
    def onred(self, widget):
 
-
        if widget.get_active():
 
-
            self.color[0] = 65535
 
-
        else: self.color[0] = 0
 
-
 
-
        self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(self.color[0],
 
-
            self.color[1], self.color[2]))
 
-
 
-
    def ongreen(self, widget):
 
-
        if (widget.get_active()):
 
-
            self.color[1] = 65535
 
-
        else: self.color[1] = 0
 
-
 
-
        self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(self.color[0],
 
-
            self.color[1], self.color[2]))
 
-
 
-
    def onblue(self, widget):
 
-
        if (widget.get_active()):
 
-
            self.color[2] = 65535
 
-
        else: self.color[2] = 0
 
-
 
-
        self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(self.color[0],
 
-
            self.color[1], self.color[2]))
 
-
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
In our example, we show three toggle buttons and a <b>DrawingArea</b>. We set the background color of the area to black. The togglebuttons will toggle the red,  green and blue parts of the color value. The background color will depend on which togglebuttons we have pressed.
 
-
 
-
<source lang="python">
 
-
self.color = [0, 0, 0]
 
-
</source>
 
-
 
-
This is the color value that is going to be updated with the toggle buttons.
 
-
 
-
<source lang="python">
 
-
red = gtk.ToggleButton("Red")
 
-
red.set_size_request(80, 35)
 
-
red.connect("clicked", self.onred)
 
-
</source>
 
-
 
-
The <b>ToggleButton</b> widget is created. We set it's size to 80x35 pixels. Each of the toggle buttons has it's own handler method.
 
-
 
-
<source lang="python">
 
-
self.darea = gtk.DrawingArea()
 
-
self.darea.set_size_request(150, 150)
 
-
self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("black"))
 
-
</source>
 
-
 
-
The <b>DrawingArea</b> widget is the widget, that displays the color, mixed by the toggle buttons. At start, it shows black color.
 
-
 
-
<source lang="python">
 
-
if widget.get_active():
 
-
    self.color[0] = 65535
 
-
else: self.color[0] = 0
 
-
</source>
 
-
 
-
If the toggle button is pressed, we change the R, G or B part of the color accordingly.
 
-
 
-
<source lang="python">
 
-
self.darea.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(self.color[0],
 
-
            self.color[1], self.color[2]))
 
-
</source>
 
-
 
-
We update the color of the <b>DrawingArea</b> widget.
 
-
 
-
[[image: pygtk_faq_togglebuttons.png | center]]
 
-
 
-
== Calendar ==
 
-
Our final widget is the <b>Calendar</b> widget. It is used to  work with dates.
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
# ZetCode PyGTK tutorial
 
-
#
 
-
# This example demonstrates the Calendar widget
 
-
#
 
-
# author: jan bodnar
 
-
# website: zetcode.com
 
-
# last edited: February 2009
 
-
 
-
import gtk
 
-
 
-
class PyApp(gtk.Window):
 
-
 
-
    def __init__(self):
 
-
        super(PyApp, self).__init__()
 
-
 
-
        self.set_title("Calendar")
 
-
        self.set_size_request(300, 270)
 
-
        self.set_position(gtk.WIN_POS_CENTER)
 
-
        self.set_border_width(2)
 
-
 
-
        self.label = gtk.Label("...")
 
-
 
-
        calendar = gtk.Calendar()
 
-
        calendar.connect("day_selected", self.on_day_selected)
 
-
 
-
        fix = gtk.Fixed()
 
-
        fix.put(calendar, 20, 20)
 
-
        fix.put(self.label, 40, 230)
 
-
 
-
        self.add(fix)
 
-
 
-
        self.connect("destroy", gtk.main_quit)
 
-
        self.show_all()
 
-
       
 
-
    def on_day_selected(self, widget):
 
-
        (year, month, day) = widget.get_date()
 
-
        self.label.set_label(str(month) + "/" + str(day) + "/" + str(year))
 
-
 
-
PyApp()
 
-
gtk.main()
 
-
</source>
 
-
 
-
We have the <b>Label</b>. The selected day from the calendar is shown in the label.
 
-
 
-
<source lang="python">
 
-
calendar = gtk.Calendar()
 
-
 
-
</source>
 
-
 
-
<b>Calendar</b> widget is created.
 
-
 
-
<source lang="python">
 
-
(year, month, day) = widget.get_date()
 
-
self.label.set_label(str(month) + "/" + str(day) + "/" + str(year))
 
-
</source>
 
-
 
-
In the <b>on_day_selected()</b> method we retrieve the currently selected date, and update the label.
 
-
 
-
[[image: pygtk_faq_calendar.png | center]]
 
-
 
-
In this chapter of the PyGTK tutorial, we finished talking about the PyGTK widgets.
 
-
 
-
[[Категория:Python]]
 
-
[[Категория:GTK+]]
 

Текущая версия на 11:25, 7 апреля 2009