Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/exercises/en/17_button-and-label_solution.py
blob: 30d644be21624efb3a05400f664a395184d31403 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python
# coding=utf-8

"""This program should display a GTK+ window containing a button and label.

You must add two widgets to the box in the window: a Gtk.Button and a
Gtk.Label.

The Gtk.Button must show the text 'Change Label'. The Gtk.Label must show the
text 'Initial label.'.

After you have added the two widgets, you must connect a callback to the
button's "clicked" signal. In this callback, you must change the Gtk.Label's
text to 'Final label.'. This means that when the program is run and the button
is clicked, the label should change its text.

You can find documentation for the Gtk.Button "clicked" signal here:
    https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked

Don't forget to document any new methods you add.

Hint: Don't forget to call the show() method on the button and label to make
them visible after adding them to the box.
"""

from gi.repository import Gtk


class SimpleWindow(Gtk.Window):
    """A simple window which displays a label and a button."""
    def __init__(self):
        super(SimpleWindow, self).__init__(title='Simple Window')

        # Set a default size for the window.
        self.set_default_size(200, 200)

        # Set up a close handler for the window. Do not modify this.
        self.connect('destroy', self.__window_destroy_cb)

        # Add a box to the window.
        box = Gtk.Box()
        box.set_orientation(Gtk.Orientation.VERTICAL)
        box.set_spacing(8)
        box.set_border_width(8)
        box.show()
        self.add(box)

        # Create and set up the label and button.
        label = Gtk.Label('Initial label.')
        label.show()
        box.pack_start(label, True, True, 0)

        button = Gtk.Button('Change Label')
        button.show()
        box.pack_start(button, False, True, 0)

        # Connect the button callback.
        button.connect('clicked', self.__button_clicked_cb)

        # Store the label as an object variable so it can be accessed from the
        # button callback.
        self._label = label

    def __button_clicked_cb(self, button):
        """Callback to change the label text when the button is clicked."""
        self._label.set_text('Final label.')

    def __window_destroy_cb(self, window):
        """Callback to quit the program when the window is closed.

        Do not modify this."""
        Gtk.main_quit()


# Run the program. Do not modify this.
SimpleWindow().show()
Gtk.main()