├── .gitattributes
├── 9781484241783.jpg
├── Tree_View_Widget
├── file.png
├── directory.png
├── SpinButtonRenderers.py
├── SpinButtonCellRenderers.py
├── PixbufRenderers.py
├── RemovingProducts.py
├── Editing_A_Cell.py
├── ComboBoxCellRenderers.py
├── GtkTreeView_GtkListStore.py
├── Using_Cell_Data_Methods.py
├── GtkTreeView_GtkListStore3.py
├── GtkTreeView_GtkListStore2.py
├── AccelCellRenderers.py
├── GtkTreeView_GtkListStore4.py
├── GtkTreeView_GtkTreeStore.py
├── PixbufRenderers2.py
└── Exercise_1.py
├── errata.md
├── Integrating
├── Calendar_File.xml
└── Calculator.py
├── Menus_And_Toolbars
├── MenuToolButton.py
├── Menu_XML_File.ui
├── Popup_UI_File.xml
├── MenuAndToolbar.py
├── Toolbar_UI_File.xml
├── SimpleMenuBar.py
├── SimplePopupMenu.py
├── SimplePopupMenu2.py
├── Exercise_2.py
├── SimpleToolbar.py
├── Exercise_1.py
├── SimplePopupMenu3.py
├── Exercise_1_Toolbar.xml
├── Exercise_2_Menubar.xml
└── SimplePopupMenu4.py
├── README.md
├── Contributing.md
├── Simple_Applications
├── HelloWorld.py
├── HelloWorld_With_Label.py
├── HelloWorld_With_Button.py
└── Exercise_1.py
├── Containers
├── Showing_And_Hiding_Widgets.py
├── Grid_Displaying_Name.py
├── Specifying_Exact_Locations.py
├── Container_With_Multiple_Pages.py
├── Horizontal_Paned_With_Buttons.py
├── Vertical_Boxes_With_Default_Packing.py
├── Vertical_Boxes_Specifying_Packing_Parameters.py
├── Adding_Events_To_GtkLabel.py
├── Exercise_2.py
└── Exercise_1.py
├── Text_View_Widget
├── GtkTextView.py
├── GtkTextBuffer_Images.py
├── GtkTextBuffer_Child.py
├── GtkTextViewProperties.py
├── UsingGtkTextView.py
├── GtkTextView_Menu.py
├── GtkTextBuffer_Search.py
├── ScrolledWindowAndViewport.py
├── GtkTextBuffer_Formatted.py
└── Exercise_1.py
├── Dynamic_User_Interfaces
├── Exercise_1.py
├── Exercise_2.py
└── LoadFileBrowser.py
├── App_and_AppWindow
├── Application1.py
└── Application2.py
├── LICENSE.txt
├── Custom_Widgets
├── CustomQuestionDialog.py
├── ImageLabelButtonClass.py
├── Alignment.py
└── Multi_Thread.py
├── Dialogs
├── GtkMessageDialogWidget.py
├── FileChooserDialog_Saving.py
├── FileChooserDialogFolderCreate.py
├── GtkMessageDialog.py
├── nonmodalGtkMessageDialog.py
├── FileChooserDialogMultipleFiles.py
├── GtkAboutDialogWidget.py
├── FontSelectionDialog.py
├── ColorSelectionDialog.py
├── SimpleDialog.py
├── Exercise_1.py
└── GtkAssistant.py
├── Basic_Widgets
├── GtkEntry.py
├── RadioButtons.py
├── GtkScaleWidgets.py
├── GtkSpinButtons.py
├── ToggleButtons.py
├── GtkColorButtonWidget.py
├── LookAlike_Stock_Button.py
├── GtkFontButtonWidget.py
├── CheckButtons.py
├── Exercise_2.py
├── Exercise_1.py
└── GtkFileChooserButtonWidget.py
└── More_Widgets
├── GtkEntryCompletion.py
├── DrawingArea.py
└── GtkPrintOperation.py
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/9781484241783.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/foundations-of-pygtk-development/HEAD/9781484241783.jpg
--------------------------------------------------------------------------------
/Tree_View_Widget/file.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/foundations-of-pygtk-development/HEAD/Tree_View_Widget/file.png
--------------------------------------------------------------------------------
/Tree_View_Widget/directory.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/foundations-of-pygtk-development/HEAD/Tree_View_Widget/directory.png
--------------------------------------------------------------------------------
/errata.md:
--------------------------------------------------------------------------------
1 | # Errata for *Book Title*
2 |
3 | On **page xx** [Summary of error]:
4 |
5 | Details of error here. Highlight key pieces in **bold**.
6 |
7 | ***
8 |
9 | On **page xx** [Summary of error]:
10 |
11 | Details of error here. Highlight key pieces in **bold**.
12 |
13 | ***
--------------------------------------------------------------------------------
/Integrating/Calendar_File.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Independence Day
4 | Everywhere
5 | 4
6 | 7
7 | 2018
8 | All Day
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/MenuToolButton.py:
--------------------------------------------------------------------------------
1 | recent = Gtk.Menu.new()
2 | # Add a number of menu items where each corresponds to one recent file.
3 | icon_theme = Gtk.IconTheme.get_default()
4 | icon = icon_theme.load_icon("document-open", -1,
5 | Gtk.IconLookupFlags.FORCE_SIZE)
6 | image = Gtk.Image.new_from_pixbuf(icon)
7 | open = Gtk.MenuToolButton.new(image, label)
8 | open.set_menu(recent)
9 |
--------------------------------------------------------------------------------
/Tree_View_Widget/SpinButtonRenderers.py:
--------------------------------------------------------------------------------
1 | def cell_edited(self, renderer, path, new_text, treeview):
2 | # Retrieve the current value stored by the spin button renderer's adjustment.
3 | adjustment = renderer.get_property("adjustment")
4 | value = "%.0f" % adjustment.get_value()
5 | model = treeview.get_model()
6 | iter = model.get_iter_from_string(path)
7 | if iter:
8 | model.set(iter, QUANTITY, value)
9 |
--------------------------------------------------------------------------------
/Tree_View_Widget/SpinButtonCellRenderers.py:
--------------------------------------------------------------------------------
1 | def setup_tree_view(self, renderer, column, adj):
2 | adj = Gtk.Adjustment.new(0.0, 0.0, 100.0, 1.0, 2.0, 2.0)
3 | renderer = Gtk.CellRendererSpin(editable=True, adjustment=adj, digits=0)
4 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
5 | treeview.append_column(column)
6 | renderer.connect("edited", self.cell_edited, treeview)
7 |
8 | # Add a cell renderer for the PRODUCT column
9 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Menu_XML_File.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
18 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Popup_UI_File.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
15 |
16 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Apress Source Code
2 |
3 | This repository accompanies [*Foundations of PyGTK Development*](https://www.apress.com/9781484241783) by W. David Ashley and Andrew Krause (Apress, 2019).
4 |
5 | [comment]: #cover
6 | 
7 |
8 | Download the files as a zip using the green button, or clone the repository to your machine using Git.
9 |
10 | ## Releases
11 |
12 | Release v1.0 corresponds to the code in the published book, without corrections or updates.
13 |
14 | ## Contributions
15 |
16 | See the file Contributing.md for more information on how you can contribute to this repository.
--------------------------------------------------------------------------------
/Tree_View_Widget/PixbufRenderers.py:
--------------------------------------------------------------------------------
1 | def set_up_treeview(self, treeview):
2 | column = Gtk.TreeViewColumn.new()
3 | column.set_resizable(True)
4 | column.set_title("Some Items")
5 | renderer = Gtk.CellRendererPixbuf.new()
6 | # it is important to pack the renderer BEFORE adding attributes!!
7 | column.pack_start(renderer, False)
8 | column.add_attribute(renderer, "pixbuf", ICON)
9 | renderer = Gtk.CellRendererText.new()
10 | # it is important to pack the renderer BEFORE adding attributes!!
11 | column.pack_start(renderer, True)
12 | column.add_attribute(renderer, "text", ICON_NAME)
13 | treeview.append_column(column)
14 |
--------------------------------------------------------------------------------
/Contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to Apress Source Code
2 |
3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers.
4 |
5 | ## How to Contribute
6 |
7 | 1. Make sure you have a GitHub account.
8 | 2. Fork the repository for the relevant book.
9 | 3. Create a new branch on which to make your change, e.g.
10 | `git checkout -b my_code_contribution`
11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted.
12 | 5. Submit a pull request.
13 |
14 | Thank you for your contribution!
--------------------------------------------------------------------------------
/Simple_Applications/HelloWorld.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 |
13 | class Application(Gtk.Application):
14 |
15 | def __init__(self, *args, **kwargs):
16 | super().__init__(*args, application_id="org.example.myapp",
17 | **kwargs)
18 | self.window = None
19 |
20 | def do_activate(self):
21 | if not self.window:
22 | self.window = AppWindow(application=self, title="Main Window")
23 | self.window.present()
24 |
25 | if __name__ == "__main__":
26 | app = Application()
27 | app.run(sys.argv)
28 |
--------------------------------------------------------------------------------
/Simple_Applications/HelloWorld_With_Label.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | label = Gtk.Label.new("Hello World!")
13 | label.set_selectable(True)
14 | self.add(label)
15 | self.set_size_request(200, 100)
16 |
17 | class Application(Gtk.Application):
18 |
19 | def __init__(self, *args, **kwargs):
20 | super().__init__(*args, application_id="org.example.myapp",
21 | **kwargs)
22 | self.window = None
23 |
24 | def do_activate(self):
25 | if not self.window:
26 | self.window = AppWindow(application=self,
27 | title="Hello World!")
28 | self.window.show_all()
29 | self.window.present()
30 |
31 | if __name__ == "__main__":
32 | app = Application()
33 | app.run(sys.argv)
34 |
--------------------------------------------------------------------------------
/Tree_View_Widget/RemovingProducts.py:
--------------------------------------------------------------------------------
1 | def remove_row(self, ref, model):
2 | # Convert the tree row reference to a path and retrieve the iterator.
3 | path = ref.get_path()
4 | iter = model.get_iter(path)
5 | # Only remove the row if it is not a root row.
6 | parent = model.iter_parent(iter)
7 | if parent:
8 | (buy, quantity) = model.get(iter, BUY_IT, QUANTITY)
9 | (pnum,) = model.get(parent, QUANTITY)
10 | if (buy):
11 | pnum -= quantity
12 | model.set(parent, QUANTITY, pnum)
13 | iter = model.get_iter(path)
14 | model.remove(iter)
15 |
16 | def remove_products(self, button, treeview):
17 | selection = treeview.get_selection()
18 | model = treeview.get_model()
19 | rows = selection.get_selected_rows(model)
20 | # Create tree row references to all of the selected rows.
21 | references = []
22 | for data in rows:
23 | ref = Gtk.TreeRowReference.new(model, data)
24 | references.append(ref)
25 | for ref in references:
26 | self.remove_row(ref, model)
27 |
--------------------------------------------------------------------------------
/Containers/Showing_And_Hiding_Widgets.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 100)
14 | expander = Gtk.Expander.new_with_mnemonic("Click _Me For More!")
15 | label = Gtk.Label.new ("Hide me or show me,\nthat is your choice.")
16 | expander.add(label)
17 | expander.set_expanded(True)
18 | self.add(expander)
19 |
20 | class Application(Gtk.Application):
21 |
22 | def __init__(self, *args, **kwargs):
23 | super().__init__(*args, application_id="org.example.myapp",
24 | **kwargs)
25 | self.window = None
26 |
27 | def do_activate(self):
28 | if not self.window:
29 | self.window = AppWindow(application=self, title="Hello World!")
30 | self.window.show_all()
31 | self.window.present()
32 |
33 | if __name__ == "__main__":
34 | app = Application()
35 | app.run(sys.argv)
36 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextView.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, 150)
14 | textview = Gtk.TextView.new()
15 | buffer = textview.get_buffer()
16 | text = "Your 1st GtkTextView widget!"
17 | buffer.set_text(text, len(text))
18 | scrolled_win = Gtk.ScrolledWindow.new (None, None)
19 | scrolled_win.add(textview)
20 | self.add(scrolled_win)
21 |
22 | class Application(Gtk.Application):
23 |
24 | def __init__(self, *args, **kwargs):
25 | super().__init__(*args, application_id="org.example.myapp",
26 | **kwargs)
27 | self.window = None
28 |
29 | def do_activate(self):
30 | if not self.window:
31 | self.window = AppWindow(application=self, title="Text Views")
32 | self.window.show_all()
33 | self.window.present()
34 |
35 | if __name__ == "__main__":
36 | app = Application()
37 | app.run(sys.argv)
38 |
--------------------------------------------------------------------------------
/Simple_Applications/HelloWorld_With_Button.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(25)
13 | button = Gtk.Button.new_with_mnemonic("_Close")
14 | button.connect("clicked", self.on_button_clicked)
15 | button.set_relief(Gtk.ReliefStyle.NORMAL)
16 | self.add(button)
17 | self.set_size_request(200, 100)
18 |
19 | def on_button_clicked(self, button):
20 | self.destroy()
21 |
22 | class Application(Gtk.Application):
23 |
24 | def __init__(self, *args, **kwargs):
25 | super().__init__(*args, application_id="org.example.myapp",
26 | **kwargs)
27 | self.window = None
28 |
29 | def do_activate(self):
30 | if not self.window:
31 | self.window = AppWindow(application=self,
32 | title="Hello World!")
33 | self.window.show_all()
34 | self.window.present()
35 |
36 | if __name__ == "__main__":
37 | app = Application()
38 | app.run(sys.argv)
39 |
--------------------------------------------------------------------------------
/Tree_View_Widget/Editing_A_Cell.py:
--------------------------------------------------------------------------------
1 | def set_up_treeview(self, treeview):
2 | renderer = Gtk.CellRenderer.Text.new()
3 | column = Gtk.TreeViewColumn.new_with_attributes("Buy", renderer,
4 | "text", BUY_IT)
5 | treeview.append_column(column)
6 | renderer = Gtk.CellRendererText.new()
7 | column = Gtk.TreeViewColumn.new_with_attributes("Count", renderer,
8 | "text", QUANTITY)
9 | treeview.append_column(column)
10 |
11 | # Set up the third column in the tree view to be editable.
12 | renderer = Gtk.CellRendererText.new()
13 | renderer.set_property("editable", True)
14 | renderer.connect("edited", self.cell_edited, treeview)
15 | column = Gtk.TreeViewColumn.new_with_attributes("Product", renderer,
16 | "text", PRODUCT)
17 | treeview.append_column(column)
18 |
19 | def cell_edited(self, renderer, path, new_text, treeview):
20 | if len(new_text) > 0:
21 | model = treeview.get_model()
22 | iter = model.get_iter_from_string(path)
23 | if iter:
24 | model.set(iter, PRODUCT, new_text)
25 |
--------------------------------------------------------------------------------
/Dynamic_User_Interfaces/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class SignalHandlers():
9 |
10 | def on_new_clicked(self, button ):
11 | pass
12 |
13 | def on_open_clicked(self, button ):
14 | pass
15 |
16 | def on_save_clicked(self, button ):
17 | pass
18 |
19 | def on_cut_clicked(self, button ):
20 | pass
21 |
22 | def on_copy_clicked(self, button ):
23 | pass
24 |
25 | def on_paste_clicked(self, button ):
26 | pass
27 |
28 | class Application(Gtk.Application):
29 |
30 | def __init__(self, *args, **kwargs):
31 | super().__init__(*args, application_id="org.example.myapp",
32 | **kwargs)
33 | self.window = None
34 |
35 | def do_activate(self):
36 | if not self.window:
37 | builder = Gtk.Builder()
38 | builder.add_from_file("./Exercise_1.glade")
39 | self.window = builder.get_object("window")
40 | self.add_window(self.window)
41 | builder.connect_signals(SignalHandlers())
42 | self.add_window(self.window)
43 | self.window.show_all()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Dynamic_User_Interfaces/Exercise_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class SignalHandlers():
9 |
10 | def on_new_clicked(self, button ):
11 | pass
12 |
13 | def on_open_clicked(self, button ):
14 | pass
15 |
16 | def on_save_clicked(self, button ):
17 | pass
18 |
19 | def on_cut_clicked(self, button ):
20 | pass
21 |
22 | def on_copy_clicked(self, button ):
23 | pass
24 |
25 | def on_paste_clicked(self, button ):
26 | pass
27 |
28 | class Application(Gtk.Application):
29 |
30 | def __init__(self, *args, **kwargs):
31 | super().__init__(*args, application_id="org.example.myapp",
32 | **kwargs)
33 | self.window = None
34 |
35 | def do_activate(self):
36 | if not self.window:
37 | builder = Gtk.Builder()
38 | builder.add_from_file("./Exercise_2.glade")
39 | self.window = builder.get_object("window")
40 | self.add_window(self.window)
41 | builder.connect_signals(SignalHandlers())
42 | self.add_window(self.window)
43 | self.window.show_all()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Containers/Grid_Displaying_Name.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(150, 100)
14 | grid = Gtk.Grid.new()
15 | label1 = Gtk.Label.new("Enter the following information ...")
16 | label2 = Gtk.Label.new("Name: ")
17 | entry = Gtk.Entry.new()
18 | grid.attach(label1, 0, 0, 2, 1)
19 | grid.attach(label2, 0, 1, 1, 1)
20 | grid.attach(entry, 1, 1, 1, 1)
21 | grid.set_row_spacing(5)
22 | grid.set_column_spacing(5)
23 | self.add(grid)
24 |
25 | class Application(Gtk.Application):
26 |
27 | def __init__(self, *args, **kwargs):
28 | super().__init__(*args, application_id="org.example.myapp",
29 | **kwargs)
30 | self.window = None
31 |
32 | def do_activate(self):
33 | if not self.window:
34 | self.window = AppWindow(application=self, title="Tables")
35 | self.window.show_all()
36 | self.window.present()
37 |
38 | if __name__ == "__main__":
39 | app = Application()
40 | app.run(sys.argv)
41 |
--------------------------------------------------------------------------------
/Simple_Applications/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | label = Gtk.Label.new("Bunny")
13 | label.set_selectable(True)
14 | self.add(label)
15 | self.set_size_request(300, 100)
16 | self.set_resizable(False)
17 | self.connect("key-press-event", self.on_window_keypress, label)
18 |
19 | def on_window_keypress(self, window, event, label):
20 | tmp = label.get_text()
21 | label.set_text(self.get_title())
22 | self.set_title(tmp)
23 | return False
24 |
25 | class Application(Gtk.Application):
26 |
27 | def __init__(self, *args, **kwargs):
28 | super().__init__(*args, application_id="org.example.myapp",
29 | **kwargs)
30 | self.window = None
31 |
32 | def do_activate(self):
33 | if not self.window:
34 | self.window = AppWindow(application=self,
35 | title="Bugs")
36 | self.window.show_all()
37 | self.window.present()
38 |
39 | if __name__ == "__main__":
40 | app = Application()
41 | app.run(sys.argv)
42 |
--------------------------------------------------------------------------------
/Containers/Specifying_Exact_Locations.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | fixed = Gtk.Fixed.new()
14 | button1 = Gtk.Button.new_with_label("Pixel by pixel ...")
15 | button2 = Gtk.Button.new_with_label("you choose my fate.")
16 | button1.connect("clicked", self.on_button_clicked)
17 | button2.connect("clicked", self.on_button_clicked)
18 | fixed.put(button1, 0, 0)
19 | fixed.put(button2, 22, 35)
20 | self.add(fixed)
21 | self.show_all()
22 |
23 | def on_button_clicked(self, widget):
24 | self.destroy()
25 |
26 | class Application(Gtk.Application):
27 |
28 | def __init__(self, *args, **kwargs):
29 | super().__init__(*args, application_id="org.example.myapp",
30 | **kwargs)
31 | self.window = None
32 |
33 | def do_activate(self):
34 | if not self.window:
35 | self.window = AppWindow(application=self, title="Fixed")
36 | self.window.show_all()
37 | self.window.present()
38 |
39 | if __name__ == "__main__":
40 | app = Application()
41 | app.run(sys.argv)
42 |
--------------------------------------------------------------------------------
/App_and_AppWindow/Application1.py:
--------------------------------------------------------------------------------
1 | class Application(Gtk.Application):
2 |
3 | def __init__(self, *args, **kwargs):
4 | super().__init__(*args, application_id="org.example.myapp",
5 | flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
6 | **kwargs)
7 | self.window = None
8 | self.add_main_option("test", ord("t"), GLib.OptionFlags.NONE,
9 | GLib.OptionArg.NONE, "Command line test", None)
10 |
11 | def do_startup(self):
12 | Gtk.Application.do_startup(self)
13 | action = Gio.SimpleAction.new("quit", None)
14 | action.connect("activate", self.on_quit)
15 | self.add_action(action)
16 |
17 | def do_activate(self):
18 | # We only allow a single window and raise any existing ones
19 | if not self.window:
20 | # Windows are associated with the application
21 | # when the last one is closed the application shuts down
22 | self.window = AppWindow(application=self, title="Main Window")
23 | self.window.present()
24 |
25 | def do_command_line(self, command_line):
26 | options = command_line.get_options_dict()
27 | if options.contains("test"):
28 | # This is printed on the main instance
29 | print("Test argument recieved")
30 | self.activate()
31 | return 0
32 |
--------------------------------------------------------------------------------
/Containers/Container_With_Multiple_Pages.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, 100)
14 | notebook = Gtk.Notebook.new()
15 | label1 = Gtk.Label.new("Page 1")
16 | label2 = Gtk.Label.new("Page 2")
17 | child1 = Gtk.Label.new("Go to page 2 to find the answer.")
18 | child2 = Gtk.Label.new("Go to page 1 to find the answer.")
19 | notebook.append_page(child1, label1)
20 | notebook.append_page(child2, label2)
21 |
22 | notebook.set_tab_pos(Gtk.PositionType.BOTTOM)
23 | self.add(notebook)
24 |
25 | class Application(Gtk.Application):
26 |
27 | def __init__(self, *args, **kwargs):
28 | super().__init__(*args, application_id="org.example.myapp",
29 | **kwargs)
30 | self.window = None
31 |
32 | def do_activate(self):
33 | if not self.window:
34 | self.window = AppWindow(application=self, title="Notebook")
35 | self.window.show_all()
36 | self.window.present()
37 |
38 | if __name__ == "__main__":
39 | app = Application()
40 | app.run(sys.argv)
41 |
--------------------------------------------------------------------------------
/Containers/Horizontal_Paned_With_Buttons.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | hpaned = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)
14 | button1 = Gtk.Button.new_with_label("Resize")
15 | button2 = Gtk.Button.new_with_label("Me!")
16 | button1.connect("clicked", self.on_button_clicked)
17 | button2.connect("clicked", self.on_button_clicked)
18 | hpaned.add1(button1)
19 | hpaned.add2(button2)
20 | self.add(hpaned)
21 | self.set_size_request(225, 150)
22 | self.show_all()
23 |
24 | def on_button_clicked(self, button):
25 | self.destroy()
26 |
27 | class Application(Gtk.Application):
28 |
29 | def __init__(self, *args, **kwargs):
30 | super().__init__(*args, application_id="org.example.myapp",
31 | **kwargs)
32 | self.window = None
33 |
34 | def do_activate(self):
35 | if not self.window:
36 | self.window = AppWindow(application=self, title="Panes")
37 | self.window.show_all()
38 | self.window.present()
39 |
40 | if __name__ == "__main__":
41 | app = Application()
42 | app.run(sys.argv)
43 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Freeware License, some rights reserved
2 |
3 | Copyright (c) 2019 W. David Ashley and Andrew Krause
4 |
5 | Permission is hereby granted, free of charge, to anyone obtaining a copy
6 | of this software and associated documentation files (the "Software"),
7 | to work with the Software within the limits of freeware distribution and fair use.
8 | This includes the rights to use, copy, and modify the Software for personal use.
9 | Users are also allowed and encouraged to submit corrections and modifications
10 | to the Software for the benefit of other users.
11 |
12 | It is not allowed to reuse, modify, or redistribute the Software for
13 | commercial use in any way, or for a user’s educational materials such as books
14 | or blog articles without prior permission from the copyright holder.
15 |
16 | The above copyright notice and this permission notice need to be included
17 | in all copies or substantial portions of the software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | SOFTWARE.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/MenuAndToolbar.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 |
13 | def change_label(self):
14 | pass
15 |
16 | def maximize(self):
17 | pass
18 |
19 | def about(self):
20 | pass
21 |
22 | def quit(self):
23 | self.destroy()
24 |
25 | def newstandard(self):
26 | pass
27 |
28 | class Application(Gtk.Application):
29 |
30 | def __init__(self, *args, **kwargs):
31 | super().__init__(*args, application_id="org.example.myapp",
32 | **kwargs)
33 | self.window = None
34 |
35 | def do_activate(self):
36 | if not self.window:
37 | self.window = AppWindow(application=self,
38 | title="Hello World!")
39 | builder = Gtk.Builder()
40 | builder.add_from_file("./Menu_XML_File.ui")
41 | builder.add_from_file("./Toolbar_UI_File.xml")
42 | builder.connect_signals(self.window)
43 | self.set_menubar(builder.get_object("menubar"))
44 | self.window.add(builder.get_object("toolbar"))
45 | self.window.present()
46 |
47 | if __name__ == "__main__":
48 | app = Application()
49 | app.run(sys.argv)
50 |
--------------------------------------------------------------------------------
/Containers/Vertical_Boxes_With_Default_Packing.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | names = ["Andrew", "Joe", "Samantha", "Jonathan"]
9 |
10 | class AppWindow(Gtk.ApplicationWindow):
11 |
12 | def __init__(self, *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
15 | for name in names:
16 | button = Gtk.Button.new_with_label(name)
17 | vbox.pack_start(button, True, True, 0)
18 | button.connect("clicked", self.on_button_clicked)
19 | button.set_relief(Gtk.ReliefStyle.NORMAL)
20 | self.set_border_width(10)
21 | self.set_size_request(200, -1)
22 | self.add(vbox)
23 | self.show_all()
24 |
25 | def on_button_clicked(self, widget):
26 | self.destroy()
27 |
28 |
29 | class Application(Gtk.Application):
30 |
31 | def __init__(self, *args, **kwargs):
32 | super().__init__(*args, application_id="org.example.myapp",
33 | **kwargs)
34 | self.window = None
35 |
36 | def do_activate(self):
37 | if not self.window:
38 | self.window = AppWindow(application=self, title="Boxes")
39 | self.window.show_all()
40 | self.window.present()
41 |
42 | if __name__ == "__main__":
43 | app = Application()
44 | app.run(sys.argv)
45 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Toolbar_UI_File.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
34 |
35 |
--------------------------------------------------------------------------------
/Containers/Vertical_Boxes_Specifying_Packing_Parameters.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | names = ["Andrew", "Joe", "Samantha", "Jonathan"]
9 |
10 | class AppWindow(Gtk.ApplicationWindow):
11 |
12 | def __init__(self, *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
15 | for name in names:
16 | button = Gtk.Button.new_with_label(name)
17 | vbox.pack_end(button, False, False, 5)
18 | button.connect("clicked", self.on_button_clicked)
19 | button.set_relief(Gtk.ReliefStyle.NORMAL)
20 | self.set_border_width(10)
21 | self.set_size_request(200, -1)
22 | self.add(vbox)
23 | self.show_all()
24 |
25 | def on_button_clicked(self, widget):
26 | self.destroy()
27 |
28 |
29 | class Application(Gtk.Application):
30 |
31 | def __init__(self, *args, **kwargs):
32 | super().__init__(*args, application_id="org.example.myapp",
33 | **kwargs)
34 | self.window = None
35 |
36 | def do_activate(self):
37 | if not self.window:
38 | self.window = AppWindow(application=self, title="Boxes")
39 | self.window.show_all()
40 | self.window.present()
41 |
42 | if __name__ == "__main__":
43 | app = Application()
44 | app.run(sys.argv)
45 |
--------------------------------------------------------------------------------
/Custom_Widgets/CustomQuestionDialog.py:
--------------------------------------------------------------------------------
1 |
2 | class ooQuestionDialog(Gtk.Dialog):
3 |
4 | hbox = None
5 | vbox = None
6 |
7 | def __init__(self, title="Error!", parent=None,
8 | flags=Gtk.DialogFlags.MODAL,
9 | buttons=("NO", Gtk.ResponseType.NO, "_YES",
10 | Gtk.ResponseType.YES)):
11 | super().__init__(title=title, parent=parent, flags=flags,
12 | buttons=buttons)
13 | self.vbox = self.get_content_area()
14 | self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
15 | spacing=5)
16 | icon_theme = Gtk.IconTheme.get_default()
17 | icon = icon_theme.load_icon("dialog-question", 48,
18 | Gtk.IconLookupFlags.FORCE_SVG)
19 | image = Gtk.Image.new_from_pixbuf(icon)
20 | self.hbox.pack_start(image, False, False, 5)
21 | self.vbox.add(self.hbox)
22 |
23 | def set_message(self, message, add_msg=None):
24 | self.hbox.pack_start(Gtk.Label(message), False, False, 5)
25 | if add_msg != None:
26 | expander = Gtk.Expander.new_with_mnemonic( \
27 | "_Click me for more information.")
28 | expander.add(Gtk.Label(add_msg))
29 | self.vbox.pack_start(expander, False, False, 10)
30 |
31 | def run(self):
32 | self.show_all()
33 | response = super().run()
34 | self.destroy()
35 | return response
36 |
--------------------------------------------------------------------------------
/Dialogs/GtkMessageDialogWidget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | button = Gtk.Button.new_with_mnemonic("_Click Me")
14 | button.connect("clicked", self.on_button_clicked, self)
15 | self.add(button)
16 | self.set_size_request(150, 50)
17 |
18 | def on_button_clicked(self, button, parent):
19 | dialog = Gtk.MessageDialog(type=Gtk.MessageType.INFO, parent=parent,
20 | flags=Gtk.DialogFlags.MODAL,
21 | buttons=("Ok", Gtk.ResponseType.OK),
22 | text="The button was clicked.",
23 | title="Information")
24 | dialog.run()
25 | dialog.destroy()
26 |
27 | class Application(Gtk.Application):
28 |
29 | def __init__(self, *args, **kwargs):
30 | super().__init__(*args, application_id="org.example.myapp",
31 | **kwargs)
32 | self.window = None
33 |
34 | def do_activate(self):
35 | if not self.window:
36 | self.window = AppWindow(application=self, title="Dialogs")
37 | self.window.show_all()
38 | self.window.present()
39 |
40 | if __name__ == "__main__":
41 | app = Application()
42 | app.run(sys.argv)
43 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkEntry.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | import os
8 |
9 | class AppWindow(Gtk.ApplicationWindow):
10 |
11 | def __init__(self, *args, **kwargs):
12 | super().__init__(*args, **kwargs)
13 | self.set_border_width(10)
14 | prompt_str = "What is the password for " + os.getlogin() + "?"
15 | question = Gtk.Label(prompt_str)
16 | label = Gtk.Label("Password:")
17 | passwd = Gtk.Entry()
18 | passwd.set_visibility(False)
19 | passwd.set_invisible_char("*")
20 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
21 | hbox.pack_start(label, False, False, 5)
22 | hbox.pack_start(passwd, False, False, 5)
23 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
24 | vbox.pack_start(question, False, False, 0)
25 | vbox.pack_start(hbox, False, False, 0)
26 | self.add(vbox)
27 |
28 | class Application(Gtk.Application):
29 |
30 | def __init__(self, *args, **kwargs):
31 | super().__init__(*args, application_id="org.example.myapp",
32 | **kwargs)
33 | self.window = None
34 |
35 | def do_activate(self):
36 | if not self.window:
37 | self.window = AppWindow(application=self, title="Password")
38 | self.window.show_all()
39 | self.window.present()
40 |
41 | if __name__ == "__main__":
42 | app = Application()
43 | app.run(sys.argv)
44 |
--------------------------------------------------------------------------------
/Basic_Widgets/RadioButtons.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | radio1 = Gtk.RadioButton.new_with_label(None, "I want to be clicked!")
14 | radio2 = Gtk.RadioButton.new_with_label_from_widget(radio1, "Click me instead!")
15 | radio3 = Gtk.RadioButton.new_with_label_from_widget(radio1, "No! Click me!")
16 | radio4 = Gtk.RadioButton.new_with_label_from_widget(radio3, "No! Click me instead!")
17 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
18 | vbox.pack_start(radio1, False, False, 0)
19 | vbox.pack_start(radio2, False, False, 0)
20 | vbox.pack_start(radio3, False, False, 0)
21 | vbox.pack_start(radio4, False, False, 0)
22 | self.add(vbox)
23 | self.show_all()
24 |
25 | class Application(Gtk.Application):
26 |
27 | def __init__(self, *args, **kwargs):
28 | super().__init__(*args, application_id="org.example.myapp",
29 | **kwargs)
30 | self.window = None
31 |
32 | def do_activate(self):
33 | if not self.window:
34 | self.window = AppWindow(application=self, title="Radio Buttons")
35 | self.window.show_all()
36 | self.window.present()
37 |
38 | if __name__ == "__main__":
39 | app = Application()
40 | app.run(sys.argv)
41 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkScaleWidgets.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | scale_int = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL,
15 | 0.0, 10.0, 1.0)
16 | scale_float = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL,
17 | 0.0, 1.0, 0.1)
18 | scale_int.set_digits(0)
19 | scale_float.set_digits(1)
20 | scale_int.set_value_pos(Gtk.PositionType.RIGHT)
21 | scale_float.set_value_pos(Gtk.PositionType.LEFT)
22 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
23 | vbox.pack_start(scale_int, False, False, 5)
24 | vbox.pack_start(scale_float, False, False, 5)
25 | self.add(vbox)
26 |
27 | class Application(Gtk.Application):
28 |
29 | def __init__(self, *args, **kwargs):
30 | super().__init__(*args, application_id="org.example.myapp",
31 | **kwargs)
32 | self.window = None
33 |
34 | def do_activate(self):
35 | if not self.window:
36 | self.window = AppWindow(application=self, title="Scales")
37 | self.window.show_all()
38 | self.window.present()
39 |
40 | if __name__ == "__main__":
41 | app = Application()
42 | app.run(sys.argv)
43 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkSpinButtons.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | integer = Gtk.Adjustment(5.0, 0.0, 10.0, 1.0, 2.0, 2.0)
14 | float_pt = Gtk.Adjustment(5.0, 0.0, 1.0, 0.1, 0.5, 0.5)
15 | spin_int = Gtk.SpinButton()
16 | spin_int.set_adjustment(integer)
17 | spin_int.set_increments(1.0, 0)
18 | spin_int.set_digits(0)
19 | spin_float = Gtk.SpinButton()
20 | spin_float.set_adjustment(float_pt)
21 | spin_float.set_increments(0.1, 0)
22 | spin_float.set_digits(1)
23 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
24 | vbox.pack_start(spin_int, False, False, 5)
25 | vbox.pack_start(spin_float, False, False, 5)
26 | self.add(vbox)
27 | self.set_size_request(180, 100)
28 | self.show_all()
29 |
30 | class Application(Gtk.Application):
31 |
32 | def __init__(self, *args, **kwargs):
33 | super().__init__(*args, application_id="org.example.myapp",
34 | **kwargs)
35 | self.window = None
36 |
37 | def do_activate(self):
38 | if not self.window:
39 | self.window = AppWindow(application=self, title="Spin Buttons")
40 | self.window.show_all()
41 | self.window.present()
42 |
43 | if __name__ == "__main__":
44 | app = Application()
45 | app.run(sys.argv)
46 |
--------------------------------------------------------------------------------
/Basic_Widgets/ToggleButtons.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
14 | toggle1 = Gtk.ToggleButton.new_with_mnemonic("_Deactivate the other one!")
15 | toggle2 = Gtk.ToggleButton.new_with_mnemonic("_No! Deactivate that one!")
16 | toggle1.connect("toggled", self.on_button_toggled, toggle2)
17 | toggle2.connect("toggled", self.on_button_toggled, toggle1)
18 | vbox.pack_start(toggle1, True, True, 1)
19 | vbox.pack_start(toggle2, True, True, 1)
20 | self.add(vbox)
21 |
22 | def on_button_toggled(self, toggle, other_toggle):
23 | if (Gtk.ToggleButton.get_active(toggle)):
24 | other_toggle.set_sensitive(False)
25 | else:
26 | other_toggle.set_sensitive(True)
27 |
28 | class Application(Gtk.Application):
29 |
30 | def __init__(self, *args, **kwargs):
31 | super().__init__(*args, application_id="org.example.myapp",
32 | **kwargs)
33 | self.window = None
34 |
35 | def do_activate(self):
36 | if not self.window:
37 | self.window = AppWindow(application=self, title="Toggle Buttons")
38 | self.window.show_all()
39 | self.window.present()
40 |
41 | if __name__ == "__main__":
42 | app = Application()
43 | app.run(sys.argv)
44 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkColorButtonWidget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | from gi.repository import Gdk
8 |
9 | class AppWindow(Gtk.ApplicationWindow):
10 |
11 | def __init__(self, *args, **kwargs):
12 | super().__init__(*args, **kwargs)
13 | self.set_border_width(10)
14 | color = Gdk.RGBA(red=0, green=.33, blue=.66, alpha=1.0)
15 | color = Gdk.RGBA.to_color(color)
16 | button = Gtk.ColorButton.new_with_color(color)
17 | button.set_title("Select a Color!")
18 | label = Gtk.Label("Look at my color!")
19 | label.modify_fg(Gtk.StateType.NORMAL, color)
20 | button.connect("color_set", self.on_color_changed, label)
21 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
22 | hbox.pack_start(button, False, False, 5)
23 | hbox.pack_start(label, False, False, 5)
24 | self.add(hbox)
25 |
26 | def on_color_changed(self, button, label):
27 | color = button.get_color()
28 | label.modify_fg(Gtk.StateType.NORMAL, color)
29 |
30 | class Application(Gtk.Application):
31 |
32 | def __init__(self, *args, **kwargs):
33 | super().__init__(*args, application_id="org.example.myapp",
34 | **kwargs)
35 | self.window = None
36 |
37 | def do_activate(self):
38 | if not self.window:
39 | self.window = AppWindow(application=self, title="Color Button")
40 | self.window.show_all()
41 | self.window.present()
42 |
43 | if __name__ == "__main__":
44 | app = Application()
45 | app.run(sys.argv)
46 |
--------------------------------------------------------------------------------
/Tree_View_Widget/ComboBoxCellRenderers.py:
--------------------------------------------------------------------------------
1 | def setup_tree_view(self, treeview):
2 | # Create a GtkListStore that will be used for the combo box renderer.
3 | model = Gtk.ListStore.new((GObject.TYPE_STRING,
4 | GObject.TYPE_STRING))
5 | iter = model.append()
6 | model.set(iter, 0, "None")
7 | iter = model.append()
8 | model.set(iter, 0, "One")
9 | iter = model.append()
10 | model.set(iter, 0, "Half a Dozen")
11 | iter = model.append()
12 | model.set(iter, 0, "Dozen")
13 | iter = model.append()
14 | model.set(iter, 0, "Two Dozen")
15 | # Create the GtkCellRendererCombo and add the tree model. Then, add the
16 | # renderer to a new column and add the column to the GtkTreeView.
17 | renderer = Gtk.CellRendererCombo(text_column=0, editable=True,
18 | has_entry=True, model=model)
19 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
20 | treeview.append_column(column)
21 | renderer.connect("edited", self.cell_edited, treeview)
22 | renderer = Gtk.CellRendererText.new()
23 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
24 | treeview.append_column(column)
25 |
26 | def cell_edited(self, renderer, path, new_text, treeview):
27 | # Make sure the text is not empty. If not, apply it to the tree view cell.
28 | if new_text != "":
29 | model = treeview.get_model()
30 | iter = model.get_iter_from_string(path)
31 | if iter:
32 | model.set(iter, QUANTITY, new_text)
33 |
--------------------------------------------------------------------------------
/Containers/Adding_Events_To_GtkLabel.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 50)
14 | eventbox = Gtk.EventBox.new()
15 | label = Gtk.Label.new("Double-Click Me!")
16 | eventbox.set_above_child(False)
17 | eventbox.connect("button_press_event", self.on_button_pressed, label)
18 | eventbox.add(label)
19 | self.add(eventbox)
20 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
21 | eventbox.realize()
22 |
23 | def on_button_pressed(self, eventbox, event, label):
24 | if event.type == Gdk.EventType._2BUTTON_PRESS:
25 | text = label.get_text()
26 | if text[0] == 'D':
27 | label.set_text("I Was Double-Clicked!")
28 | else:
29 | label.set_text("Double-Click Me Again!")
30 | return False
31 |
32 | class Application(Gtk.Application):
33 |
34 | def __init__(self, *args, **kwargs):
35 | super().__init__(*args, application_id="org.example.myapp",
36 | **kwargs)
37 | self.window = None
38 |
39 | def do_activate(self):
40 | if not self.window:
41 | self.window = AppWindow(application=self, title="Hello World!")
42 | self.window.show_all()
43 | self.window.present()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Dynamic_User_Interfaces/LoadFileBrowser.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class SignalHandlers():
9 |
10 | def on_back_clicked(self, button ):
11 | pass
12 |
13 | def on_forward_clicked(self, button ):
14 | pass
15 |
16 | def on_up_clicked(self, button ):
17 | pass
18 |
19 | def on_refresh_clicked(self, button ):
20 | pass
21 |
22 | def on_home_clicked(self, button ):
23 | pass
24 |
25 | def on_delete_clicked(self, button ):
26 | pass
27 |
28 | def on_info_clicked(self, button ):
29 | pass
30 |
31 | def on_go_clicked(self, button ):
32 | pass
33 |
34 | def on_location_activate(self, button ):
35 | pass
36 |
37 | def on_row_activated(self, button ):
38 | pass
39 |
40 | def on_window_destroy(self, button ):
41 | pass
42 |
43 | class Application(Gtk.Application):
44 |
45 | def __init__(self, *args, **kwargs):
46 | super().__init__(*args, application_id="org.example.myapp",
47 | **kwargs)
48 | self.window = None
49 |
50 | def do_activate(self):
51 | if not self.window:
52 | builder = Gtk.Builder()
53 | builder.add_from_file("./FileBrowser.glade")
54 | self.window = builder.get_object("main_window")
55 | self.add_window(self.window)
56 | builder.connect_signals(SignalHandlers())
57 | self.add_window(self.window)
58 | self.window.show_all()
59 |
60 | if __name__ == "__main__":
61 | app = Application()
62 | app.run(sys.argv)
63 |
--------------------------------------------------------------------------------
/Basic_Widgets/LookAlike_Stock_Button.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | button = Gtk.Button.new()
14 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
15 | icon_theme = Gtk.IconTheme.get_default()
16 | icon = icon_theme.load_icon("window-close", -1,
17 | Gtk.IconLookupFlags.FORCE_SIZE)
18 | image = Gtk.Image.new_from_pixbuf(icon)
19 | hbox.add(image)
20 | label = Gtk.Label.new_with_mnemonic("_Close")
21 | hbox.add(label)
22 | hbox.set_homogeneous(True)
23 | button.add(hbox)
24 | button.connect("clicked", self.on_button_clicked)
25 | button.set_relief(Gtk.ReliefStyle.NORMAL)
26 | self.add(button)
27 | self.set_size_request(230, 100)
28 |
29 | def on_button_clicked(self, param):
30 | self.destroy()
31 |
32 | class Application(Gtk.Application):
33 |
34 | def __init__(self, *args, **kwargs):
35 | super().__init__(*args, application_id="org.example.myapp",
36 | **kwargs)
37 | self.window = None
38 |
39 | def do_activate(self):
40 | if not self.window:
41 | self.window = AppWindow(application=self, title="Look-alike Stock Item")
42 | self.window.show_all()
43 | self.window.present()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextBuffer_Images.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 150)
14 | textview = Gtk.TextView.new()
15 | buffer = textview.get_buffer()
16 | text = " Undo\n Redo"
17 | buffer.set_text(text, len(text))
18 | icon_theme = Gtk.IconTheme.get_default()
19 | undo = icon_theme.load_icon("edit-undo", -1,
20 | Gtk.IconLookupFlags.FORCE_SIZE)
21 | line = buffer.get_iter_at_line (0)
22 | buffer.insert_pixbuf(line, undo)
23 | redo = icon_theme.load_icon("edit-redo", -1,
24 | Gtk.IconLookupFlags.FORCE_SIZE)
25 | line = buffer.get_iter_at_line (1)
26 | buffer.insert_pixbuf(line, redo)
27 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
28 | scrolled_win.add(textview)
29 | self.add (scrolled_win)
30 |
31 | class Application(Gtk.Application):
32 |
33 | def __init__(self, *args, **kwargs):
34 | super().__init__(*args, application_id="org.example.myapp",
35 | **kwargs)
36 | self.window = None
37 |
38 | def do_activate(self):
39 | if not self.window:
40 | self.window = AppWindow(application=self, title="Pixbufs")
41 | self.window.show_all()
42 | self.window.present()
43 |
44 | if __name__ == "__main__":
45 | app = Application()
46 | app.run(sys.argv)
47 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkFontButtonWidget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | from gi.repository import Pango
8 |
9 | class AppWindow(Gtk.ApplicationWindow):
10 |
11 | def __init__(self, *args, **kwargs):
12 | super().__init__(*args, **kwargs)
13 | self.set_border_width(10)
14 | label = Gtk.Label("Look at the font!")
15 | initial_font = Pango.font_description_from_string("Sans Bold 12")
16 | label.modify_font(initial_font)
17 | button = Gtk.FontButton.new_with_font("Sans Bold 12")
18 | button.set_title("Choose a Font")
19 | button.connect("font_set", self.on_font_changed, label)
20 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
21 | vbox.pack_start(button, False, False, 0)
22 | vbox.pack_start(label, False, False, 0)
23 | self.add(vbox)
24 |
25 | def on_font_changed(self, button, label):
26 | font = button.get_font()
27 | desc = Pango.font_description_from_string(font)
28 | buffer = "Font: " + font
29 | label.set_text(buffer)
30 | label.modify_font(desc)
31 |
32 | class Application(Gtk.Application):
33 |
34 | def __init__(self, *args, **kwargs):
35 | super().__init__(*args, application_id="org.example.myapp",
36 | **kwargs)
37 | self.window = None
38 |
39 | def do_activate(self):
40 | if not self.window:
41 | self.window = AppWindow(application=self, title="Font Button")
42 | self.window.show_all()
43 | self.window.present()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Dialogs/FileChooserDialog_Saving.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 100)
14 | button = Gtk.Button.new_with_label("Save as ...")
15 | button.connect("clicked", self.on_button_clicked, self)
16 | self.add(button)
17 |
18 | def on_button_clicked(self, button, parentwin):
19 | dialog = Gtk.FileChooserDialog(title="Save file as ...",
20 | parent=parentwin,
21 | action=Gtk.FileChooserAction.SAVE,
22 | buttons=("_Cancel",
23 | Gtk.ResponseType.CANCEL,
24 | "_Save", Gtk.ResponseType.ACCEPT))
25 | response = dialog.run()
26 | if response == Gtk.ResponseType.ACCEPT:
27 | filename = dialog.get_filename()
28 | button.set_label(filename)
29 | dialog.destroy()
30 |
31 | class Application(Gtk.Application):
32 |
33 | def __init__(self, *args, **kwargs):
34 | super().__init__(*args, application_id="org.example.myapp",
35 | **kwargs)
36 | self.window = None
37 |
38 | def do_activate(self):
39 | if not self.window:
40 | self.window = AppWindow(application=self, title="Save a File")
41 | self.window.show_all()
42 | self.window.present()
43 |
44 | if __name__ == "__main__":
45 | app = Application()
46 | app.run(sys.argv)
47 |
--------------------------------------------------------------------------------
/More_Widgets/GtkEntryCompletion.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | widgets = ["GtkDialog", "GtkWindow", "GtkContainer", "GtkWidget"]
13 | self.set_border_width(10)
14 | label = Gtk.Label.new("Enter a widget in the following GtkEntry:")
15 | entry = Gtk.Entry.new()
16 | # Create a GtkListStore that will hold autocompletion possibilities.
17 | types = (GObject.TYPE_STRING,)
18 | store = Gtk.ListStore.new(types)
19 | for widget in widgets:
20 | iter = store.append()
21 | store.set(iter, 0, widget)
22 | completion = Gtk.EntryCompletion.new()
23 | entry.set_completion(completion)
24 | completion.set_model(store)
25 | completion.set_text_column(0)
26 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
27 | vbox.pack_start(label, False, False, 0)
28 | vbox.pack_start(entry, False, False, 0)
29 | self.add(vbox)
30 |
31 | class Application(Gtk.Application):
32 |
33 | def __init__(self, *args, **kwargs):
34 | super().__init__(*args, application_id="org.example.myapp",
35 | **kwargs)
36 | self.window = None
37 |
38 | def do_activate(self):
39 | if not self.window:
40 | self.window = AppWindow(application=self,
41 | title="Automatic Completion")
42 | self.window.show_all()
43 | self.window.present()
44 |
45 | if __name__ == "__main__":
46 | app = Application()
47 | app.run(sys.argv)
48 |
--------------------------------------------------------------------------------
/Dialogs/FileChooserDialogFolderCreate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 100)
14 | button = Gtk.Button.new_with_label("Create a Folder ...")
15 | button.connect("clicked", self.on_button_clicked, self)
16 | self.add(button)
17 |
18 | def on_button_clicked(self, button, parentwin):
19 | dialog = Gtk.FileChooserDialog(title="Create a Folder ...",
20 | parent=parentwin,
21 | action=Gtk.FileChooserAction.SAVE,
22 | buttons=("_Cancel",
23 | Gtk.ResponseType.CANCEL,
24 | "_Ok", Gtk.ResponseType.OK))
25 | response = dialog.run()
26 | if response == Gtk.ResponseType.OK:
27 | filename = dialog.get_filename();
28 | print("Creating directory: %s\n" % filename)
29 | dialog.destroy()
30 |
31 | class Application(Gtk.Application):
32 |
33 | def __init__(self, *args, **kwargs):
34 | super().__init__(*args, application_id="org.example.myapp",
35 | **kwargs)
36 | self.window = None
37 |
38 | def do_activate(self):
39 | if not self.window:
40 | self.window = AppWindow(application=self, title="Create Folder")
41 | self.window.show_all()
42 | self.window.present()
43 |
44 | if __name__ == "__main__":
45 | app = Application()
46 | app.run(sys.argv)
47 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextBuffer_Child.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(25)
13 | self.set_border_width(10)
14 | self.set_size_request(250, 100)
15 | textview = Gtk.TextView.new()
16 | buffer = textview.get_buffer()
17 | text = "\n Click to exit!"
18 | buffer.set_text(text, len(text))
19 | iter = buffer.get_iter_at_offset(8)
20 | anchor = buffer.create_child_anchor(iter)
21 | button = Gtk.Button.new_with_label("the button")
22 | button.connect("clicked", self.on_button_clicked)
23 | button.set_relief(Gtk.ReliefStyle.NORMAL)
24 | textview.add_child_at_anchor(button, anchor)
25 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
26 | scrolled_win.add(textview)
27 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC,
28 | Gtk.PolicyType.ALWAYS)
29 | self.add(scrolled_win)
30 |
31 | def on_button_clicked(self, button):
32 | self.destroy()
33 |
34 | class Application(Gtk.Application):
35 |
36 | def __init__(self, *args, **kwargs):
37 | super().__init__(*args, application_id="org.example.myapp",
38 | **kwargs)
39 | self.window = None
40 |
41 | def do_activate(self):
42 | if not self.window:
43 | self.window = AppWindow(application=self, title="Child Widgets")
44 | self.window.show_all()
45 | self.window.present()
46 |
47 | if __name__ == "__main__":
48 | app = Application()
49 | app.run(sys.argv)
50 |
--------------------------------------------------------------------------------
/Basic_Widgets/CheckButtons.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | check1 = Gtk.CheckButton.new_with_label("I am the main option.")
14 | check2 = Gtk.CheckButton.new_with_label("I rely on the other guy.")
15 | check2.set_sensitive(False)
16 | check1.connect("toggled", self.on_button_checked, check2)
17 | closebutton = Gtk.Button.new_with_mnemonic("_Close")
18 | closebutton.connect("clicked", self.on_button_close_clicked)
19 | vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
20 | vbox.pack_start(check1, False, True, 0)
21 | vbox.pack_start(check2, False, True, 0)
22 | vbox.pack_start(closebutton, False, True, 0)
23 | self.add(vbox)
24 |
25 | def on_button_checked(self, check1, check2):
26 | if check1.get_active():
27 | check2.set_sensitive(True);
28 | else:
29 | check2.set_sensitive(False)
30 |
31 | def on_button_close_clicked(self, button):
32 | self.destroy()
33 |
34 | class Application(Gtk.Application):
35 |
36 | def __init__(self, *args, **kwargs):
37 | super().__init__(*args, application_id="org.example.myapp",
38 | **kwargs)
39 | self.window = None
40 |
41 | def do_activate(self):
42 | if not self.window:
43 | self.window = AppWindow(application=self, title="Check Buttons")
44 | self.window.show_all()
45 | self.window.present()
46 |
47 | if __name__ == "__main__":
48 | app = Application()
49 | app.run(sys.argv)
50 |
--------------------------------------------------------------------------------
/Dialogs/GtkMessageDialog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | button = Gtk.Button.new_with_mnemonic("_Click Me")
14 | button.connect("clicked", self.on_button_clicked, self)
15 | self.add(button)
16 | self.set_size_request(150, 50)
17 |
18 | def on_button_clicked(self, button, parent):
19 | dialog = Gtk.Dialog(title="Information", parent=parent,
20 | flags=Gtk.DialogFlags.MODAL)
21 | dialog.add_button("Ok", Gtk.ResponseType.OK)
22 | label = Gtk.Label("The button was clicked.")
23 | image = Gtk.Image.new_from_icon_name("dialog-information",
24 | Gtk.IconSize.DIALOG)
25 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
26 | hbox.pack_start(image, False, False, 0)
27 | hbox.pack_start(label, False, False, 0)
28 | dialog.vbox.pack_start(hbox, False, False, 0)
29 | dialog.show_all()
30 | dialog.run()
31 | dialog.destroy()
32 |
33 | class Application(Gtk.Application):
34 |
35 | def __init__(self, *args, **kwargs):
36 | super().__init__(*args, application_id="org.example.myapp",
37 | **kwargs)
38 | self.window = None
39 |
40 | def do_activate(self):
41 | if not self.window:
42 | self.window = AppWindow(application=self, title="Dialogs")
43 | self.window.show_all()
44 | self.window.present()
45 |
46 | if __name__ == "__main__":
47 | app = Application()
48 | app.run(sys.argv)
49 |
--------------------------------------------------------------------------------
/Dialogs/nonmodalGtkMessageDialog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | button = Gtk.Button.new_with_mnemonic("_Click Me")
14 | button.connect("clicked", self.on_button_clicked, self)
15 | self.add(button)
16 | self.set_size_request(150, 50)
17 | self.show_all()
18 |
19 | def on_button_clicked(self, button, parent):
20 | dialog = Gtk.Dialog(title="Information", parent=parent)
21 | dialog.add_button("Ok", Gtk.ResponseType.OK)
22 | label = Gtk.Label("The button was clicked.")
23 | image = Gtk.Image.new_from_icon_name("dialog-information",
24 | Gtk.IconSize.DIALOG)
25 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
26 | hbox.pack_start(image, False, False, 0)
27 | hbox.pack_start(label, False, False, 0)
28 | dialog.vbox.pack_start(hbox, False, False, 0)
29 | dialog.connect("response", self.on_dialog_button_clicked)
30 | dialog.show_all()
31 |
32 | def on_dialog_button_clicked(self, dialog, response):
33 | dialog.destroy()
34 |
35 | class Application(Gtk.Application):
36 |
37 | def __init__(self, *args, **kwargs):
38 | super().__init__(*args, application_id="org.example.myapp",
39 | **kwargs)
40 | self.window = None
41 |
42 | def do_activate(self):
43 | if not self.window:
44 | self.window = AppWindow(application=self, title="Dialogs")
45 | self.window.show_all()
46 | self.window.present()
47 |
48 | if __name__ == "__main__":
49 | app = Application()
50 | app.run(sys.argv)
51 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextViewProperties.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Pango
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, 150)
14 | font = Pango.font_description_from_string("Monospace Bold 10")
15 | textview = Gtk.TextView.new()
16 | textview.modify_font(font)
17 | textview.set_wrap_mode(Gtk.WrapMode.WORD)
18 | textview.set_justification(Gtk.Justification.RIGHT)
19 | textview.set_editable(True)
20 | textview.set_cursor_visible(True)
21 | textview.set_pixels_above_lines(5)
22 | textview.set_pixels_below_lines(5)
23 | textview.set_pixels_inside_wrap(5)
24 | textview.set_left_margin(10)
25 | textview.set_right_margin(10)
26 | buffer = textview.get_buffer()
27 | text = "This is some text!\nChange me!\nPlease!"
28 | buffer.set_text(text, len(text))
29 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
30 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC,
31 | Gtk.PolicyType.ALWAYS)
32 | scrolled_win.add(textview)
33 | self.add(scrolled_win)
34 |
35 | class Application(Gtk.Application):
36 |
37 | def __init__(self, *args, **kwargs):
38 | super().__init__(*args, application_id="org.example.myapp",
39 | **kwargs)
40 | self.window = None
41 |
42 | def do_activate(self):
43 | if not self.window:
44 | self.window = AppWindow(application=self,
45 | title="Text Views Properties")
46 | self.window.show_all()
47 | self.window.present()
48 |
49 | if __name__ == "__main__":
50 | app = Application()
51 | app.run(sys.argv)
52 |
--------------------------------------------------------------------------------
/Dialogs/FileChooserDialogMultipleFiles.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 100)
14 | button = Gtk.Button.new_with_label("Open file(s) ...")
15 | button.connect("clicked", self.on_button_clicked, self)
16 | self.add(button)
17 |
18 | def on_button_clicked(self, button, parentwin):
19 | dialog = Gtk.FileChooserDialog(title="Open file(s) ...",
20 | parent=parentwin,
21 | action=Gtk.FileChooserAction.OPEN,
22 | buttons=("_Cancel",
23 | Gtk.ResponseType.CANCEL,
24 | "_Open", Gtk.ResponseType.ACCEPT))
25 | dialog.set_select_multiple(True)
26 | response = dialog.run()
27 | if response == Gtk.ResponseType.ACCEPT:
28 | filenames = dialog.get_filenames()
29 | i = 0
30 | while i < len(filenames):
31 | file = filenames[i]
32 | print(file + " was selected.")
33 | i += 1
34 | dialog.destroy()
35 |
36 | class Application(Gtk.Application):
37 |
38 | def __init__(self, *args, **kwargs):
39 | super().__init__(*args, application_id="org.example.myapp",
40 | **kwargs)
41 | self.window = None
42 |
43 | def do_activate(self):
44 | if not self.window:
45 | self.window = AppWindow(application=self,
46 | title="Open Nultiple Files")
47 | self.window.show_all()
48 | self.window.present()
49 |
50 | if __name__ == "__main__":
51 | app = Application()
52 | app.run(sys.argv)
53 |
--------------------------------------------------------------------------------
/Basic_Widgets/Exercise_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | import os
8 | from pathlib import Path
9 |
10 | class AppWindow(Gtk.ApplicationWindow):
11 |
12 | def __init__(self, *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | self.set_border_width(10)
15 |
16 | adj1 = Gtk.Adjustment.new(0.5, 0.0, 1.0, 0.01, 0.02, 0.02)
17 | adj2 = Gtk.Adjustment.new(0.5, 0.0, 1.02, 0.01, 0.02, 0.02)
18 |
19 | spin = Gtk.SpinButton.new(adj1, 0.01, 2)
20 | scale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, adj2)
21 | check = Gtk.CheckButton.new_with_label("Synchronize Spin and Scale")
22 |
23 | check.set_active(True)
24 | scale.set_digits(2)
25 | scale.set_value_pos(Gtk.PositionType.RIGHT)
26 |
27 | spin.connect("value_changed", self.on_spin_value_changed, spin, scale, check)
28 | scale.connect("value_changed", self.on_scale_value_changed, spin, scale, check)
29 |
30 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5);
31 | vbox.pack_start(spin, False, True, 0)
32 | vbox.pack_start(scale, False, True, 0);
33 | vbox.pack_start(check, False, True, 0);
34 |
35 | self.add(vbox)
36 |
37 |
38 | def on_spin_value_changed(self, widget, spin, scale, check):
39 | val1 = spin.get_value()
40 | val2 = scale.get_value()
41 |
42 | if (check.get_active() and val1 != val2):
43 | if isinstance(widget, Gtk.SpinButton):
44 | scale.set_value(val1)
45 | else:
46 | spin.set_value(val2)
47 |
48 |
49 |
50 | class Application(Gtk.Application):
51 |
52 | def __init__(self, *args, **kwargs):
53 | super().__init__(*args, application_id="org.example.myapp",
54 | **kwargs)
55 | self.window = None
56 |
57 | def do_activate(self):
58 | if not self.window:
59 | self.window = AppWindow(application=self, title="Exercise 2")
60 | self.window.show_all()
61 | self.window.present()
62 |
63 | if __name__ == "__main__":
64 | app = Application()
65 | app.run(sys.argv)
66 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimpleMenuBar.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_size_request(250, -1)
13 | menubar = Gtk.MenuBar.new()
14 | file = Gtk.MenuItem.new_with_label("File")
15 | edit = Gtk.MenuItem.new_with_label("Edit")
16 | help = Gtk.MenuItem.new_with_label("Help")
17 | filemenu = Gtk.Menu.new()
18 | editmenu = Gtk.Menu.new()
19 | helpmenu = Gtk.Menu.new()
20 | file.set_submenu(filemenu)
21 | edit.set_submenu(editmenu)
22 | help.set_submenu(helpmenu)
23 | menubar.append(file)
24 | menubar.append(edit)
25 | menubar.append(help)
26 | # Create the File menu content.
27 | new = Gtk.MenuItem.new_with_label("New")
28 | open = Gtk.MenuItem.new_with_label("Open")
29 | filemenu.append(new)
30 | filemenu.append(open)
31 | # Create the Edit menu content.
32 | cut = Gtk.MenuItem.new_with_label("Cut")
33 | copy = Gtk.MenuItem.new_with_label("Copy")
34 | paste = Gtk.MenuItem.new_with_label("Paste")
35 | editmenu.append(cut)
36 | editmenu.append(copy)
37 | editmenu.append(paste)
38 | # Create the Help menu content.
39 | contents = Gtk.MenuItem.new_with_label("Help")
40 | about = Gtk.MenuItem.new_with_label("About")
41 | helpmenu.append(contents)
42 | helpmenu.append(about)
43 | self.add(menubar)
44 |
45 | class Application(Gtk.Application):
46 |
47 | def __init__(self, *args, **kwargs):
48 | super().__init__(*args, application_id="org.example.myapp",
49 | **kwargs)
50 | self.window = None
51 |
52 | def do_activate(self):
53 | if not self.window:
54 | self.window = AppWindow(application=self,
55 | title="Menu Bars")
56 | self.window.show_all()
57 | self.window.present()
58 |
59 | if __name__ == "__main__":
60 | app = Application()
61 | app.run(sys.argv)
62 |
--------------------------------------------------------------------------------
/Dialogs/GtkAboutDialogWidget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GdkPixbuf
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | button = Gtk.Button.new_with_mnemonic("_Click Me")
14 | button.connect("clicked", self.on_button_clicked, self)
15 | self.add(button)
16 | self.set_size_request(150, 50)
17 | self.show_all()
18 |
19 | def on_button_clicked(self, button, parent):
20 | authors = ["Author #1", "Author #2"]
21 | documenters = ["Documenter #1", "Documenter #2"]
22 | dialog = Gtk.AboutDialog(parent=parent)
23 | logo = GdkPixbuf.Pixbuf.new_from_file("./logo.png")
24 | if logo != None:
25 | dialog.set_logo(logo)
26 | else:
27 | print("A GdkPixbuf Error has occurred.")
28 | dialog.set_name("Gtk.AboutDialog")
29 | dialog.set_version("3.0")
30 | dialog.set_copyright("(C) 2007 Andrew Krause")
31 | dialog.set_comments("All about Gtk.AboutDialog")
32 | dialog.set_license("Free to all!")
33 | dialog.set_website("http://book.andrewKrause.net")
34 | dialog.set_website_label("book.andrewkrause.net")
35 | dialog.set_authors(authors)
36 | dialog.set_documenters(documenters)
37 | dialog.set_translator_credits("Translator #1\nTranslator #2")
38 | dialog.connect("response", self.on_dialog_button_clicked)
39 | dialog.run()
40 |
41 | def on_dialog_button_clicked(self, dialog, response):
42 | dialog.destroy()
43 |
44 | class Application(Gtk.Application):
45 |
46 | def __init__(self, *args, **kwargs):
47 | super().__init__(*args, application_id="org.example.myapp",
48 | **kwargs)
49 | self.window = None
50 |
51 | def do_activate(self):
52 | if not self.window:
53 | self.window = AppWindow(application=self, title="About Dialog")
54 | self.window.show_all()
55 | self.window.present()
56 |
57 | if __name__ == "__main__":
58 | app = Application()
59 | app.run(sys.argv)
60 |
--------------------------------------------------------------------------------
/Text_View_Widget/UsingGtkTextView.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(-1, -1)
14 | textview = Gtk.TextView.new()
15 | entry = Gtk.Entry.new()
16 | insert_button = Gtk.Button.new_with_label("Insert Text")
17 | retrieve = Gtk.Button.new_with_label("Get Text")
18 | insert_button.connect("clicked", self.on_insert_text, (entry, textview))
19 | retrieve.connect("clicked", self.on_retrieve_text, (entry, textview))
20 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
21 | scrolled_win.add(textview)
22 | hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
23 | hbox.pack_start(entry, True, True, 0)
24 | hbox.pack_start(insert_button, True, True, 0)
25 | hbox.pack_start(retrieve, True, True, 0)
26 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
27 | vbox.pack_start(scrolled_win, True, True, 0)
28 | vbox.pack_start(hbox, True, True, 0)
29 | self.add(vbox)
30 | self.show_all()
31 |
32 | def on_insert_text(self, button, w):
33 | buffer = w[1].get_buffer()
34 | text = w[0].get_text()
35 | mark = buffer.get_insert()
36 | iter = buffer.get_iter_at_mark(mark)
37 | buffer.insert(iter, text, len(text))
38 |
39 | def on_retrieve_text(self, button, w):
40 | buffer = w[1].get_buffer()
41 | (start, end) = buffer.get_selection_bounds()
42 | text = buffer.get_text(start, end, False)
43 | print(text)
44 |
45 | class Application(Gtk.Application):
46 |
47 | def __init__(self, *args, **kwargs):
48 | super().__init__(*args, application_id="org.example.myapp",
49 | **kwargs)
50 | self.window = None
51 |
52 | def do_activate(self):
53 | if not self.window:
54 | self.window = AppWindow(application=self, title="Text Iterators")
55 | self.window.show_all()
56 | self.window.present()
57 |
58 | if __name__ == "__main__":
59 | app = Application()
60 | app.run(sys.argv)
61 |
--------------------------------------------------------------------------------
/Dialogs/FontSelectionDialog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(200, 100)
14 | button = Gtk.Button.new_with_label("Run Font Selection Dialog")
15 | button.connect("clicked", self.on_run_font_selection_dialog)
16 | self.add(button)
17 |
18 | def on_run_font_selection_dialog(self, button):
19 | dialog = Gtk.FontSelectionDialog(title="Choose a Font",
20 | buttons=("Apply", Gtk.ResponseType.APPLY),
21 | parent=self)
22 | dialog.set_preview_text("GTK+ 3 Development With Python")
23 | dialog.connect("response", self.on_dialog_response)
24 | # dialog.show_all()
25 | dialog.run()
26 |
27 | def on_dialog_response(self, dialog, response):
28 | if response == Gtk.ResponseType.OK or response == Gtk.ResponseType.APPLY:
29 | font = dialog.get_font_name()
30 | message = Gtk.MessageDialog(title="Selected Font",
31 | flags=Gtk.DialogFlags.MODAL,
32 | type=Gtk.MessageType.INFO,
33 | text=font,
34 | buttons=("Ok", Gtk.ResponseType.OK),
35 | parent=dialog);
36 | message.run()
37 | message.destroy()
38 | if response == Gtk.ResponseType.OK:
39 | dialog.destroy()
40 | else:
41 | dialog.destroy()
42 |
43 | class Application(Gtk.Application):
44 |
45 | def __init__(self, *args, **kwargs):
46 | super().__init__(*args, application_id="org.example.myapp",
47 | **kwargs)
48 | self.window = None
49 |
50 | def do_activate(self):
51 | if not self.window:
52 | self.window = AppWindow(application=self, title="Font Selection Dialog")
53 | self.window.show_all()
54 | self.window.present()
55 |
56 | if __name__ == "__main__":
57 | app = Application()
58 | app.run(sys.argv)
59 |
--------------------------------------------------------------------------------
/Basic_Widgets/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | import os
8 | from pathlib import Path
9 |
10 | class AppWindow(Gtk.ApplicationWindow):
11 |
12 | def __init__(self, *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | self.set_border_width(10)
15 |
16 | rnm = Gtk.Button.new_with_label("Apply")
17 | name = Gtk.Entry.new()
18 | rnm.set_sensitive(False)
19 | name.set_sensitive(False)
20 |
21 | file = Gtk.FileChooserButton("Choose File", Gtk.FileChooserAction.OPEN)
22 | file.set_current_folder(str(Path.home()))
23 |
24 | file.connect("selection-changed", self.on_file_changed, file, rnm,
25 | name)
26 | rnm.connect("clicked", self.on_rename_clicked, file, rnm, name)
27 |
28 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
29 | hbox.pack_start(name, True, True, 0)
30 | hbox.pack_start(rnm, False, True, 0)
31 |
32 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
33 | vbox.pack_start(file, False, True, 0)
34 | vbox.pack_start(hbox, False, True, 0)
35 |
36 | self.add(vbox)
37 |
38 |
39 | def on_file_changed(self, chooser, file, rnm, name):
40 | fn = file.get_filename()
41 | mode = os.access(fn, os.W_OK)
42 |
43 | rnm.set_sensitive(mode)
44 | name.set_sensitive(mode)
45 |
46 | def on_rename_clicked(self, chooser, file, rnm, name):
47 | old = file.get_filename()
48 | location = file.get_current_folder()
49 | new = location + "/" + name.get_text()
50 |
51 | os.rename(old, new)
52 | rnm.set_sensitive(False)
53 | name.set_sensitive(False)
54 |
55 | class Application(Gtk.Application):
56 |
57 | def __init__(self, *args, **kwargs):
58 | super().__init__(*args, application_id="org.example.myapp",
59 | **kwargs)
60 | self.window = None
61 |
62 | def do_activate(self):
63 | if not self.window:
64 | self.window = AppWindow(application=self, title="File Chooser Button Exercise")
65 | self.window.show_all()
66 | self.window.present()
67 |
68 | if __name__ == "__main__":
69 | app = Application()
70 | app.run(sys.argv)
71 |
--------------------------------------------------------------------------------
/Custom_Widgets/ImageLabelButtonClass.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class ImageLabelButton(Gtk.Button):
9 |
10 | def __init__(self, orientation=Gtk.Orientation.HORIZONTAL,
11 | image="image-missing", label="Missing",
12 | *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | # now set up more properties
15 | hbox = Gtk.Box(orientation, spacing=0)
16 | if not isinstance(image, str):
17 | raise TypeError("Expected str, got %s instead." % str(image))
18 | icon_theme = Gtk.IconTheme.get_default()
19 | icon = icon_theme.load_icon(image, -1,
20 | Gtk.IconLookupFlags.FORCE_SIZE)
21 | img = Gtk.Image.new_from_pixbuf(icon)
22 | hbox.pack_start(img, True, True, 0)
23 | img.set_halign(Gtk.Align.END)
24 | if not isinstance(label, str):
25 | raise TypeError("Expected str, got %s instead." % str(label))
26 | if len(label) > 15:
27 | raise ValueError("The length of str may not exceed 15 characters.")
28 | labelwidget = Gtk.Label(label)
29 | hbox.pack_start(labelwidget, True, True, 0)
30 | labelwidget.set_halign(Gtk.Align.START)
31 | self.add(hbox)
32 |
33 | class AppWindow(Gtk.ApplicationWindow):
34 |
35 | def __init__(self, *args, **kwargs):
36 | super().__init__(*args, **kwargs)
37 | self.set_border_width(25)
38 | button = ImageLabelButton(image="window-close", label="Close")
39 | button.connect("clicked", self.on_button_clicked)
40 | button.set_relief(Gtk.ReliefStyle.NORMAL)
41 | self.add(button)
42 | self.set_size_request(170, 50)
43 |
44 | def on_button_clicked(self, button):
45 | self.destroy()
46 |
47 | class Application(Gtk.Application):
48 |
49 | def __init__(self, *args, **kwargs):
50 | super().__init__(*args, application_id="org.example.myapp",
51 | **kwargs)
52 | self.window = None
53 |
54 | def do_activate(self):
55 | if not self.window:
56 | self.window = AppWindow(application=self,
57 | title="ImageLabelButton")
58 | self.window.show_all()
59 | self.window.present()
60 |
61 | if __name__ == "__main__":
62 | app = Application()
63 | app.run(sys.argv)
64 |
--------------------------------------------------------------------------------
/Custom_Widgets/Alignment.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.resize(300, 100)
14 | # create a grid
15 | grid1 = Gtk.Grid()
16 | grid1.height = 2
17 | grid1.width = 2
18 | grid1.set_column_homogeneous(True)
19 | grid1.set_row_homogeneous(True)
20 | self.add(grid1)
21 | # build the aligned labels
22 | label1 = Gtk.Label('Top left Aligned')
23 | label1.can_focus = False
24 | label1.set_halign(Gtk.Align.START)
25 | label1.set_valign(Gtk.Align.START)
26 | grid1.attach(label1, 0, 0, 1, 1)
27 | label2 = Gtk.Label('Top right Aligned')
28 | label2.can_focus = False
29 | label2.set_halign(Gtk.Align.END)
30 | label2.set_valign(Gtk.Align.START)
31 | grid1.attach(label2, 1, 0, 1, 1)
32 | label3 = Gtk.Label('Bottom left Aligned')
33 | label3.can_focus = False
34 | label3.set_halign(Gtk.Align.START)
35 | label3.set_valign(Gtk.Align.END)
36 | grid1.attach(label3, 0, 1, 1, 1)
37 | label4 = Gtk.Label('Bottom right Aligned')
38 | label4.can_focus = False
39 | label4.set_halign(Gtk.Align.END)
40 | label4.set_valign(Gtk.Align.END)
41 | grid1.attach(label4, 1, 1, 1, 1)
42 |
43 | class Application(Gtk.Application):
44 |
45 | def __init__(self, *args, **kwargs):
46 | super().__init__(*args, application_id="org.example.myapp",
47 | **kwargs)
48 | self.window = None
49 | gtk_version = float(str(Gtk.MAJOR_VERSION)+'.'+str(Gtk.MINOR_VERSION))
50 | if gtk_version < 3.16:
51 | print('There is a bug in versions of GTK older that 3.16.')
52 | print('Your version is not new enough to prevent this bug from')
53 | print('causing problems in the display of this solution.')
54 | exit(0)
55 |
56 | def do_activate(self):
57 | if not self.window:
58 | self.window = AppWindow(application=self,
59 | title="Alignment")
60 | self.window.show_all()
61 | self.window.present()
62 |
63 | if __name__ == "__main__":
64 | app = Application()
65 | app.run(sys.argv)
66 |
--------------------------------------------------------------------------------
/Tree_View_Widget/GtkTreeView_GtkListStore.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | BUY_IT = 0
9 | QUANTITY = 1
10 | PRODUCT = 2
11 |
12 | GroceryItem = (( True, 1, "Paper Towels" ),
13 | ( True, 2, "Bread" ),
14 | ( False, 1, "Butter" ),
15 | ( True, 1, "Milk" ),
16 | ( False, 3, "Chips" ),
17 | ( True, 4, "Soda" ))
18 |
19 | class AppWindow(Gtk.ApplicationWindow):
20 |
21 | def __init__(self, *args, **kwargs):
22 | super().__init__(*args, **kwargs)
23 | self.set_border_width(10)
24 | self.set_size_request(250, 175)
25 | treeview = Gtk.TreeView.new()
26 | self.setup_tree_view(treeview)
27 | store = Gtk.ListStore.new((GObject.TYPE_BOOLEAN,
28 | GObject.TYPE_INT,
29 | GObject.TYPE_STRING))
30 | for row in GroceryItem:
31 | iter = store.append(None)
32 | store.set(iter, BUY_IT, row[BUY_IT], QUANTITY, row[QUANTITY], PRODUCT,
33 | row[PRODUCT])
34 | treeview.set_model(store)
35 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
36 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
37 | scrolled_win.add(treeview)
38 | self.add(scrolled_win)
39 |
40 | def setup_tree_view(self, treeview):
41 | renderer = Gtk.CellRendererText.new()
42 | column = Gtk.TreeViewColumn("Buy", renderer, text=BUY_IT)
43 | treeview.append_column(column)
44 | renderer = Gtk.CellRendererText.new()
45 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
46 | treeview.append_column(column)
47 | renderer = Gtk.CellRendererText.new()
48 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
49 | treeview.append_column(column)
50 |
51 | class Application(Gtk.Application):
52 |
53 | def __init__(self, *args, **kwargs):
54 | super().__init__(*args, application_id="org.example.myapp",
55 | **kwargs)
56 | self.window = None
57 |
58 | def do_activate(self):
59 | if not self.window:
60 | self.window = AppWindow(application=self, title="Grocery List")
61 | self.window.show_all()
62 | self.window.present()
63 |
64 | if __name__ == "__main__":
65 | app = Application()
66 | app.run(sys.argv)
67 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextView_Menu.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | textview = Gtk.TextView.new()
14 | cut = Gtk.Button.new_with_label("Cut")
15 | copy = Gtk.Button.new_with_label("Copy")
16 | paste = Gtk.Button.new_with_label("Paste")
17 | cut.connect("clicked", self.on_cut_clicked, textview)
18 | copy.connect("clicked", self.on_copy_clicked, textview)
19 | paste.connect("clicked", self.on_paste_clicked, textview)
20 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
21 | scrolled_win.set_size_request(300, 200)
22 | scrolled_win.add(textview)
23 | hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
24 | hbox.pack_start(cut, True, True, 0)
25 | hbox.pack_start(copy, True, True, 0)
26 | hbox.pack_start(paste, True, True, 0)
27 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
28 | vbox.pack_start(scrolled_win, True, True, 0)
29 | vbox.pack_start(hbox, True, True, 0)
30 | self.add(vbox)
31 |
32 | def on_cut_clicked(self, button, textview):
33 | clipboard = Gtk.Clipboard.get(Gdk.Atom.intern("CLIPBOARD", False))
34 | buffer = textview.get_buffer()
35 | buffer.cut_clipboard(clipboard, True)
36 |
37 | def on_copy_clicked(self, button, textview):
38 | clipboard = Gtk.Clipboard.get(Gdk.Atom.intern("CLIPBOARD", False))
39 | buffer = textview.get_buffer()
40 | buffer.copy_clipboard(clipboard)
41 |
42 | def on_paste_clicked(self, button, textview):
43 | clipboard = Gtk.Clipboard.get(Gdk.Atom.intern("CLIPBOARD", False))
44 | buffer = textview.get_buffer()
45 | buffer.paste_clipboard (clipboard, None, True)
46 |
47 | class Application(Gtk.Application):
48 |
49 | def __init__(self, *args, **kwargs):
50 | super().__init__(*args, application_id="org.example.myapp",
51 | **kwargs)
52 | self.window = None
53 |
54 | def do_activate(self):
55 | if not self.window:
56 | self.window = AppWindow(application=self, title="Cut, Copy & Paste")
57 | self.window.show_all()
58 | self.window.present()
59 |
60 | if __name__ == "__main__":
61 | app = Application()
62 | app.run(sys.argv)
63 |
--------------------------------------------------------------------------------
/Basic_Widgets/GtkFileChooserButtonWidget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | from pathlib import Path
8 |
9 | class AppWindow(Gtk.ApplicationWindow):
10 |
11 | def __init__(self, *args, **kwargs):
12 | super().__init__(*args, **kwargs)
13 | self.set_border_width(10)
14 | label = Gtk.Label("")
15 | chooser1 = Gtk.FileChooserButton("Choose a Folder.",
16 | Gtk.FileChooserAction.SELECT_FOLDER)
17 | chooser2 = Gtk.FileChooserButton("Choose a Folder.",
18 | Gtk.FileChooserAction.OPEN)
19 | chooser1.connect("selection_changed", self.on_folder_changed,
20 | chooser2)
21 | chooser2.connect("selection_changed", self.on_file_changed, label)
22 | chooser1.set_current_folder(str(Path.home()))
23 | chooser2.set_current_folder(str(Path.home()))
24 | filter1 = Gtk.FileFilter()
25 | filter2 = Gtk.FileFilter()
26 | filter1.set_name("Image Files")
27 | filter2.set_name("All Files")
28 | filter1.add_pattern("*.png")
29 | filter1.add_pattern("*.jpg")
30 | filter1.add_pattern("*.gif")
31 | filter2.add_pattern("*")
32 | chooser2.add_filter(filter1)
33 | chooser2.add_filter(filter2)
34 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
35 | vbox.pack_start(chooser1, False, False, 0)
36 | vbox.pack_start(chooser2, False, False, 0)
37 | vbox.pack_start(label, False, False, 0)
38 | self.add(vbox)
39 | self.set_size_request(240, -1)
40 |
41 | def on_folder_changed(self, chooser1, chooser2):
42 | folder = chooser1.get_filename()
43 | chooser2.set_current_folder(folder)
44 |
45 | def on_file_changed(self, chooser2, label):
46 | file = chooser2.get_filename()
47 | label.set_text(file)
48 |
49 | class Application(Gtk.Application):
50 |
51 | def __init__(self, *args, **kwargs):
52 | super().__init__(*args, application_id="org.example.myapp",
53 | **kwargs)
54 | self.window = None
55 |
56 | def do_activate(self):
57 | if not self.window:
58 | self.window = AppWindow(application=self, title="File Chooser Button")
59 | self.window.show_all()
60 | self.window.present()
61 |
62 | if __name__ == "__main__":
63 | app = Application()
64 | app.run(sys.argv)
65 |
--------------------------------------------------------------------------------
/Dialogs/ColorSelectionDialog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | global_color = Gdk.RGBA(red=.50, green=.50, blue=.50, alpha=1.0).to_color()
9 | global_alpha = 65535
10 |
11 | class AppWindow(Gtk.ApplicationWindow):
12 |
13 | def __init__(self, *args, **kwargs):
14 | super().__init__(*args, **kwargs)
15 | self.set_border_width(10)
16 | self.set_size_request(200, 100)
17 | modal = Gtk.Button.new_with_label("Modal")
18 | nonmodal = Gtk.Button.new_with_label("Non-Modal")
19 | modal.connect("clicked", self.on_run_color_selection_dialog,
20 | self, True)
21 | nonmodal.connect("clicked", self.on_run_color_selection_dialog,
22 | self, False)
23 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
24 | hbox.pack_start(modal, False, False, 5)
25 | hbox.pack_start(nonmodal, False, False, 5)
26 | self.add(hbox)
27 |
28 | def on_dialog_response(self, dialog, result):
29 | if result == Gtk.ResponseType.OK:
30 | colorsel = dialog.get_color_selection()
31 | alpha = colorsel.get_current_alpha()
32 | color = colorsel.get_current_color()
33 | print(color.to_string())
34 | global_color = color
35 | global_alpha = alpha
36 | dialog.destroy()
37 |
38 | def on_run_color_selection_dialog(self, button, window, domodal):
39 | if domodal:
40 | title = ("Choose Color -- Modal")
41 | else:
42 | title = ("Choose Color -- Non-Modal")
43 | dialog = Gtk.ColorSelectionDialog(title=title, parent=window, modal=domodal)
44 | colorsel = dialog.get_color_selection()
45 | colorsel.set_has_opacity_control(True)
46 | colorsel.set_current_color(global_color)
47 | dialog.connect("response", self.on_dialog_response)
48 | dialog.show_all()
49 |
50 | class Application(Gtk.Application):
51 |
52 | def __init__(self, *args, **kwargs):
53 | super().__init__(*args, application_id="org.example.myapp",
54 | **kwargs)
55 | self.window = None
56 |
57 | def do_activate(self):
58 | if not self.window:
59 | self.window = AppWindow(application=self, title="Color Selection Dialog")
60 | self.window.show_all()
61 | self.window.present()
62 |
63 | if __name__ == "__main__":
64 | app = Application()
65 | app.run(sys.argv)
66 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimplePopupMenu.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | # Create all of the necessary widgets and initialize the pop-up menu.
15 | menu = Gtk.Menu.new()
16 | eventbox = Gtk.EventBox.new()
17 | progress = Gtk.ProgressBar.new()
18 | progress.set_text("Nothing Yet Happened")
19 | self.create_popup_menu(menu, progress)
20 | progress.set_pulse_step(0.05)
21 | eventbox.set_above_child(False)
22 | eventbox.connect("button_press_event", self.button_press_event, menu)
23 | eventbox.add(progress)
24 | self.add(eventbox)
25 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
26 | eventbox.realize()
27 |
28 | def create_popup_menu(self, menu, progress):
29 | pulse = Gtk.MenuItem.new_with_label("Pulse Progress")
30 | fill = Gtk.MenuItem.new_with_label("Set as Complete")
31 | clear = Gtk.MenuItem.new_with_label("Clear Progress")
32 | separator = Gtk.SeparatorMenuItem.new()
33 | pulse.connect("activate", self.pulse_activated, progress)
34 | fill.connect("activate", self.fill_activated, progress)
35 | clear.connect("activate", self.clear_activated, progress)
36 | menu.append(pulse)
37 | menu.append(separator)
38 | menu.append(fill)
39 | menu.append(clear)
40 | menu.attach_to_widget(progress, None)
41 | menu.show_all()
42 |
43 | def button_press_event(self, eventbox, event, menu):
44 | pass
45 |
46 | def pulse_activated(self, item, progress):
47 | pass
48 |
49 | def fill_activated(self, item, progress):
50 | pass
51 |
52 | def clear_activated(self, item, progress):
53 | pass
54 |
55 | class Application(Gtk.Application):
56 |
57 | def __init__(self, *args, **kwargs):
58 | super().__init__(*args, application_id="org.example.myapp",
59 | **kwargs)
60 | self.window = None
61 |
62 | def do_activate(self):
63 | if not self.window:
64 | self.window = AppWindow(application=self,
65 | title="Pop-up Menus")
66 | self.window.show_all()
67 | self.window.present()
68 |
69 | if __name__ == "__main__":
70 | app = Application()
71 | app.run(sys.argv)
72 |
--------------------------------------------------------------------------------
/Containers/Exercise_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, 200)
14 |
15 | notebook = Gtk.Notebook.new()
16 | notebook.set_show_tabs(False)
17 |
18 | for i in range(0, 4):
19 | label = Gtk.Label.new("Tab")
20 | button = Gtk.Button.new_with_mnemonic("_Next Tab")
21 |
22 | expander = Gtk.Expander.new("You Are Viewing Tab %s" % str(i+1))
23 | expander.set_expanded(True)
24 | expander.add (button)
25 |
26 | notebook.append_page(expander, label)
27 | expander.set_border_width(10)
28 |
29 | button.connect("clicked", self.on_notebook_button_clicked, notebook)
30 |
31 | buttonbox = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
32 | button_prev = Gtk.Button.new_with_label("Previous Page")
33 | button_prev.connect("clicked", self.on_button_prev_clicked, notebook)
34 | button_close = Gtk.Button.new_with_label("Close")
35 | button_close.connect("clicked", self.on_button_close_clicked)
36 | buttonbox.pack_end(button_prev, False, False, 5)
37 | buttonbox.pack_end(button_close, False, False, 5)
38 |
39 | paned = Gtk.Paned.new(Gtk.Orientation.VERTICAL)
40 | paned.pack1(notebook, True, False)
41 | paned.pack2(buttonbox, True, False)
42 |
43 | self.add(paned)
44 |
45 | def on_notebook_button_clicked(self, button, notebook):
46 | nextpage = notebook.props.page + 1
47 | if nextpage == 4:
48 | nextpage = 0
49 | notebook.set_current_page(nextpage)
50 |
51 | def on_button_prev_clicked(self, button, notebook):
52 | nextpage = notebook.props.page - 1
53 | if nextpage == -1:
54 | nextpage = 3
55 | notebook.set_current_page(nextpage)
56 |
57 | def on_button_close_clicked(self, button):
58 | self.destroy()
59 |
60 | class Application(Gtk.Application):
61 |
62 | def __init__(self, *args, **kwargs):
63 | super().__init__(*args, application_id="org.example.myapp",
64 | **kwargs)
65 | self.window = None
66 |
67 | def do_activate(self):
68 | if not self.window:
69 | self.window = AppWindow(application=self, title="Notebook")
70 | self.window.show_all()
71 | self.window.present()
72 |
73 | if __name__ == "__main__":
74 | app = Application()
75 | app.run(sys.argv)
76 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextBuffer_Search.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | textview = Gtk.TextView.new()
14 | entry = Gtk.Entry.new()
15 | entry.set_text("Search for ...")
16 | find = Gtk.Button.new_with_label("Find")
17 | find.connect("clicked", self.on_find_clicked, (textview, entry))
18 | scrolled_win = Gtk.ScrolledWindow.new (None, None)
19 | scrolled_win.set_size_request(250, 200)
20 | scrolled_win.add(textview)
21 | hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
22 | hbox.pack_start(entry, True, True, 0)
23 | hbox.pack_start(find, True, True, 0)
24 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
25 | vbox.pack_start(scrolled_win, True, True, 0)
26 | vbox.pack_start(hbox, True, True, 0)
27 | self.add(vbox)
28 |
29 | def on_find_clicked(self, button, w):
30 | find = w[1].get_text()
31 | find_len = len(find)
32 | buffer = w[0].get_buffer()
33 | start = buffer.get_start_iter()
34 | end_itr = buffer.get_end_iter()
35 | i = 0
36 | while True:
37 | end = start.copy()
38 | end.forward_chars(find_len)
39 | text = buffer.get_text(start, end, False)
40 | if text == find:
41 | i += 1
42 | start.forward_chars(find_len)
43 | else:
44 | start.forward_char()
45 | if end.compare(end_itr) == 0:
46 | break
47 | output = "The string '"+find+"' was found " + str(i) + " times!"
48 | dialog = Gtk.MessageDialog(parent=self, flags=Gtk.DialogFlags.MODAL,
49 | message_type=Gtk.MessageType.INFO,
50 | text=output, title="Information",
51 | buttons=("OK", Gtk.ResponseType.OK))
52 | dialog.run()
53 | dialog.destroy()
54 |
55 | class Application(Gtk.Application):
56 |
57 | def __init__(self, *args, **kwargs):
58 | super().__init__(*args, application_id="org.example.myapp",
59 | **kwargs)
60 | self.window = None
61 |
62 | def do_activate(self):
63 | if not self.window:
64 | self.window = AppWindow(application=self, title="Searching Buffers")
65 | self.window.show_all()
66 | self.window.present()
67 |
68 | if __name__ == "__main__":
69 | app = Application()
70 | app.run(sys.argv)
71 |
--------------------------------------------------------------------------------
/Tree_View_Widget/Using_Cell_Data_Methods.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk, GObject
7 |
8 | clr = ( "00", "33", "66", "99", "CC", "FF" )
9 | COLOR = 0
10 |
11 | class AppWindow(Gtk.ApplicationWindow):
12 |
13 | def __init__(self, *args, **kwargs):
14 | super().__init__(*args, **kwargs)
15 | self.set_border_width(10)
16 | self.set_size_request(250, 175)
17 | treeview = Gtk.TreeView.new()
18 | self.setup_tree_view(treeview)
19 | store = Gtk.ListStore.new((GObject.TYPE_STRING,
20 | GObject.TYPE_STRING, GObject.TYPE_STRING))
21 | for var1 in clr:
22 | for var2 in clr:
23 | for var3 in clr:
24 | color = "#" + var1 + var2 + var3
25 | iter = store.append()
26 | store.set(iter, (COLOR,), (color,))
27 | treeview.set_model(store)
28 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
29 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
30 | scrolled_win.add(treeview)
31 | self.add(scrolled_win)
32 |
33 | def setup_tree_view(self, treeview):
34 | renderer = Gtk.CellRendererText.new()
35 | column = Gtk.TreeViewColumn.new()
36 | column.pack_start(renderer, True)
37 | column.add_attribute(renderer, "text", COLOR)
38 | column.set_title("Standard Colors")
39 | treeview.append_column(column)
40 | column.set_cell_data_func(renderer, self.cell_data_func, None)
41 |
42 | def cell_data_func(self, column, renderer, model, iter, data):
43 | # Get the color string stored by the column and make it the foreground color.
44 | (text,) = model.get(iter, COLOR)
45 | renderer.props.foreground_rgba = Gdk.RGBA(red=1.0, green=1.0, blue=1.0, alpha=1.0)
46 | red = int(text[1:3], 16) / 255
47 | green = int(text[3:5], 16) / 255
48 | blue = int(text[5:7], 16) / 255
49 | renderer.props.background_rgba = Gdk.RGBA(red=red, green=green, blue=blue, alpha=1.0)
50 | renderer.props.text = text
51 |
52 | class Application(Gtk.Application):
53 |
54 | def __init__(self, *args, **kwargs):
55 | super().__init__(*args, application_id="org.example.myapp",
56 | **kwargs)
57 | self.window = None
58 |
59 | def do_activate(self):
60 | if not self.window:
61 | self.window = AppWindow(application=self,
62 | title="Color List")
63 | self.window.show_all()
64 | self.window.present()
65 |
66 | if __name__ == "__main__":
67 | app = Application()
68 | app.run(sys.argv)
69 |
--------------------------------------------------------------------------------
/Dialogs/SimpleDialog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | import os
8 | import getpass
9 | import socket
10 | import pwd
11 |
12 | class AppWindow(Gtk.ApplicationWindow):
13 |
14 | def __init__(self, *args, **kwargs):
15 | super().__init__(*args, **kwargs)
16 | self.set_border_width(10)
17 | button = Gtk.Button.new_with_mnemonic("_Click Me")
18 | button.connect("clicked", self.on_button_clicked, self)
19 | self.add(button)
20 | self.set_size_request(180, 50)
21 | self.show_all()
22 |
23 | def on_button_clicked(self, button, parent):
24 | dialog = Gtk.Dialog(title="Edit User Information", parent=parent,
25 | flags=Gtk.DialogFlags.MODAL)
26 | dialog.add_button("Ok", Gtk.ResponseType.OK)
27 | dialog.add_button("Cancel", Gtk.ResponseType.CANCEL)
28 | dialog.set_default_response(Gtk.ResponseType.OK)
29 | lbl1 = Gtk.Label("User Name:")
30 | lbl2 = Gtk.Label("Real Name:")
31 | lbl3 = Gtk.Label("Home Dir:")
32 | lbl4 = Gtk.Label("Host Name:")
33 | user = Gtk.Entry()
34 | real_name = Gtk.Entry()
35 | home = Gtk.Entry()
36 | host = Gtk.Entry()
37 | user.set_text(getpass.getuser())
38 | real_name.set_text(pwd.getpwuid(os.getuid())[4])
39 | home.set_text(os.environ['HOME'])
40 | host.set_text(socket.gethostname())
41 | grid = Gtk.Grid()
42 | grid.attach(lbl1, 0, 0, 1, 1)
43 | grid.attach(lbl2, 0, 1, 1, 1)
44 | grid.attach(lbl3, 0, 2, 1, 1)
45 | grid.attach(lbl4, 0, 3, 1, 1)
46 | grid.attach(user, 1, 0, 1, 1)
47 | grid.attach(real_name, 1, 1, 1, 1)
48 | grid.attach(home, 1, 2, 1, 1)
49 | grid.attach(host, 1, 3, 1, 1)
50 | dialog.vbox.pack_start(grid, False, False, 5)
51 | dialog.show_all()
52 | result = dialog.run()
53 | if result == Gtk.ResponseType.OK:
54 | print("User Name: " + user.get_text())
55 | print("Real Name: " + real_name.get_text())
56 | print("Home: " + home.get_text())
57 | print("Host: " + host.get_text())
58 | dialog.destroy()
59 |
60 | class Application(Gtk.Application):
61 |
62 | def __init__(self, *args, **kwargs):
63 | super().__init__(*args, application_id="org.example.myapp",
64 | **kwargs)
65 | self.window = None
66 |
67 | def do_activate(self):
68 | if not self.window:
69 | self.window = AppWindow(application=self, title="Simple Dialog")
70 | self.window.show_all()
71 | self.window.present()
72 |
73 | if __name__ == "__main__":
74 | app = Application()
75 | app.run(sys.argv)
76 |
--------------------------------------------------------------------------------
/Tree_View_Widget/GtkTreeView_GtkListStore3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | QUANTITY = 0
9 | PRODUCT = 1
10 |
11 | GroceryItem = (( 1, "Paper Towels" ),
12 | ( 2, "Bread" ),
13 | ( 1, "Butter" ),
14 | ( 1, "Milk" ),
15 | ( 3, "Chips" ),
16 | ( 4, "Soda" ))
17 |
18 | class AppWindow(Gtk.ApplicationWindow):
19 |
20 | def __init__(self, *args, **kwargs):
21 | super().__init__(*args, **kwargs)
22 | self.set_border_width(10)
23 | self.set_size_request(250, 175)
24 | treeview = Gtk.TreeView.new()
25 | self.setup_tree_view(treeview)
26 | store = Gtk.ListStore.new((GObject.TYPE_STRING,
27 | GObject.TYPE_STRING))
28 | for row in GroceryItem:
29 | iter = store.append(None)
30 | store.set(iter, QUANTITY, "%.0f" % row[QUANTITY], PRODUCT, row[PRODUCT])
31 | treeview.set_model(store)
32 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
33 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
34 | scrolled_win.add(treeview)
35 | self.add(scrolled_win)
36 |
37 | def setup_tree_view(self, treeview):
38 | adj = Gtk.Adjustment.new(0.0, 0.0, 100.0, 1.0, 2.0, 2.0)
39 | renderer = Gtk.CellRendererSpin(editable=True, adjustment=adj, digits=0)
40 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
41 | treeview.append_column(column)
42 | renderer.connect("edited", self.cell_edited, treeview)
43 | renderer = Gtk.CellRendererText.new()
44 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
45 | treeview.append_column(column)
46 |
47 | def cell_edited(self, renderer, path, new_text, treeview):
48 | # Retrieve the current value stored by the spin button renderer's adjustment.
49 | adjustment = renderer.get_property("adjustment")
50 | value = "%.0f" % adjustment.get_value()
51 | model = treeview.get_model()
52 | iter = model.get_iter_from_string(path)
53 | if iter:
54 | model.set(iter, QUANTITY, value)
55 |
56 | class Application(Gtk.Application):
57 |
58 | def __init__(self, *args, **kwargs):
59 | super().__init__(*args, application_id="org.example.myapp",
60 | **kwargs)
61 | self.window = None
62 |
63 | def do_activate(self):
64 | if not self.window:
65 | self.window = AppWindow(application=self, title="Grocery List")
66 | self.window.show_all()
67 | self.window.present()
68 |
69 | if __name__ == "__main__":
70 | app = Application()
71 | app.run(sys.argv)
72 |
--------------------------------------------------------------------------------
/Text_View_Widget/ScrolledWindowAndViewport.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | grid1 = Gtk.Grid.new()
14 | grid2 = Gtk.Grid.new()
15 | grid1.set_column_homogeneous = True
16 | grid2.set_column_homogeneous = True
17 | grid1.set_row_homogeneous = True
18 | grid2.set_row_homogeneous = True
19 | grid1.set_column_spacing = 5
20 | grid2.set_column_spacing = 5
21 | grid1.set_row_spacing = 5
22 | grid2.set_row_spacing = 5
23 | i = 0
24 | while i < 10:
25 | j = 0
26 | while j < 10:
27 | button = Gtk.Button.new_with_label("Close")
28 | button.set_relief(Gtk.ReliefStyle.NONE)
29 | button.connect("clicked", self.on_button_clicked)
30 | grid1.attach(button, i, j, 1, 1)
31 | button = Gtk.Button.new_with_label("Close")
32 | button.set_relief(Gtk.ReliefStyle.NONE)
33 | button.connect("clicked", self.on_button_clicked)
34 | grid2.attach(button, i, j, 1, 1)
35 | j += 1
36 | i += 1
37 | swin = Gtk.ScrolledWindow.new(None, None)
38 | horizontal = swin.get_hadjustment()
39 | vertical = swin.get_vadjustment()
40 | viewport = Gtk.Viewport.new(horizontal, vertical)
41 | swin.set_border_width(5)
42 | swin.set_propagate_natural_width(True)
43 | swin.set_propagate_natural_height(True)
44 | viewport.set_border_width(5)
45 | swin.set_policy (Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
46 | swin.add_with_viewport(grid1)
47 | viewport.add(grid2)
48 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
49 | vbox.set_homogeneous = True
50 | vbox.pack_start(viewport, True, True, 5)
51 | vbox.pack_start(swin, True, True, 5)
52 | self.add (vbox)
53 | self.show_all()
54 |
55 | def on_button_clicked(self, button):
56 | self.destroy()
57 |
58 | class Application(Gtk.Application):
59 |
60 | def __init__(self, *args, **kwargs):
61 | super().__init__(*args, application_id="org.example.myapp",
62 | **kwargs)
63 | self.window = None
64 |
65 | def do_activate(self):
66 | if not self.window:
67 | self.window = AppWindow(application=self, title="Scrolled Windows & Viewports")
68 | self.window.show_all()
69 | self.window.present()
70 |
71 | if __name__ == "__main__":
72 | app = Application()
73 | app.run(sys.argv)
74 |
--------------------------------------------------------------------------------
/Tree_View_Widget/GtkTreeView_GtkListStore2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | BUY_IT = 0
9 | QUANTITY = 1
10 | PRODUCT = 2
11 |
12 | GroceryItem = (( True, 1, "Paper Towels" ),
13 | ( True, 2, "Bread" ),
14 | ( False, 1, "Butter" ),
15 | ( True, 1, "Milk" ),
16 | ( False, 3, "Chips" ),
17 | ( True, 4, "Soda" ))
18 |
19 | class AppWindow(Gtk.ApplicationWindow):
20 |
21 | def __init__(self, *args, **kwargs):
22 | super().__init__(*args, **kwargs)
23 | self.set_border_width(10)
24 | self.set_size_request(250, 175)
25 | treeview = Gtk.TreeView.new()
26 | self.setup_tree_view(treeview)
27 | store = Gtk.ListStore.new((GObject.TYPE_BOOLEAN,
28 | GObject.TYPE_INT,
29 | GObject.TYPE_STRING))
30 | for row in GroceryItem:
31 | iter = store.append(None)
32 | store.set(iter, BUY_IT, row[BUY_IT], QUANTITY, row[QUANTITY], PRODUCT,
33 | row[PRODUCT])
34 | treeview.set_model(store)
35 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
36 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
37 | scrolled_win.add(treeview)
38 | self.add(scrolled_win)
39 |
40 | def setup_tree_view(self, treeview):
41 | renderer = Gtk.CellRendererToggle.new()
42 | renderer.set_property("activatable", True)
43 | column = Gtk.TreeViewColumn("Buy", renderer, active=BUY_IT)
44 | renderer.connect("toggled", self.do_toggled, treeview)
45 | treeview.append_column(column)
46 | renderer = Gtk.CellRendererText.new()
47 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
48 | treeview.append_column(column)
49 | renderer = Gtk.CellRendererText.new()
50 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
51 | treeview.append_column(column)
52 |
53 | def do_toggled(self, renderer, path, treeview):
54 | model = treeview.get_model()
55 | iter = model.get_iter(path)
56 | if iter:
57 | (value,) = model.get(iter, BUY_IT)
58 | model.set_row(iter, (not value, None, None))
59 |
60 |
61 |
62 | class Application(Gtk.Application):
63 |
64 | def __init__(self, *args, **kwargs):
65 | super().__init__(*args, application_id="org.example.myapp",
66 | **kwargs)
67 | self.window = None
68 |
69 | def do_activate(self):
70 | if not self.window:
71 | self.window = AppWindow(application=self, title="Grocery List")
72 | self.window.show_all()
73 | self.window.present()
74 |
75 | if __name__ == "__main__":
76 | app = Application()
77 | app.run(sys.argv)
78 |
--------------------------------------------------------------------------------
/Tree_View_Widget/AccelCellRenderers.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk, GObject
7 |
8 | ACTION = 0
9 | MASK = 1
10 | VALUE = 2
11 |
12 | list = [( "Cut", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_X ),
13 | ( "Copy", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_C ),
14 | ( "Paste", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_V ),
15 | ( "New", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_N ),
16 | ( "Open", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_O ),
17 | ( "Print", Gdk.ModifierType.CONTROL_MASK, Gdk.KEY_P )]
18 |
19 | class AppWindow(Gtk.ApplicationWindow):
20 |
21 | def __init__(self, *args, **kwargs):
22 | super().__init__(*args, **kwargs)
23 | self.set_size_request(250, 250)
24 | treeview = Gtk.TreeView.new()
25 | self.setup_tree_view(treeview)
26 | store = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_INT,
27 | GObject.TYPE_UINT)
28 | for row in list:
29 | (action, mask, value) = row
30 | iter = store.append(None)
31 | store.set(iter, ACTION, action, MASK, mask, VALUE, value)
32 | treeview.set_model(store)
33 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
34 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC,
35 | Gtk.PolicyType.AUTOMATIC)
36 | scrolled_win.add(treeview)
37 | self.add(scrolled_win)
38 |
39 | def setup_tree_view(self, treeview):
40 | renderer = Gtk.CellRendererAccel()
41 | column = Gtk.TreeViewColumn("Action", renderer, text=ACTION)
42 | treeview.append_column(column)
43 | renderer = Gtk.CellRendererAccel(accel_mode=Gtk.CellRendererAccelMode.GTK,
44 | editable=True)
45 | column = Gtk.TreeViewColumn("Key", renderer, accel_mods=MASK,
46 | accel_key=VALUE)
47 | treeview.append_column(column)
48 | renderer.connect("accel_edited", self.accel_edited, treeview)
49 |
50 | def accel_edited(self, renderer, path, accel_key, mask,
51 | hardware_keycode, treeview):
52 | model = treeview.get_model()
53 | iter = model.get_iter_from_string(path)
54 | if iter:
55 | model.set(iter, MASK, mask, VALUE, accel_key)
56 |
57 | class Application(Gtk.Application):
58 |
59 | def __init__(self, *args, **kwargs):
60 | super().__init__(*args, application_id="org.example.myapp",
61 | **kwargs)
62 | self.window = None
63 |
64 | def do_activate(self):
65 | if not self.window:
66 | self.window = AppWindow(application=self,
67 | title="Accelerator Keys")
68 | self.window.show_all()
69 | self.window.present()
70 |
71 | if __name__ == "__main__":
72 | app = Application()
73 | app.run(sys.argv)
74 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimplePopupMenu2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | # Create all of the necessary widgets and initialize the pop-up menu.
15 | menu = Gtk.Menu.new()
16 | eventbox = Gtk.EventBox.new()
17 | progress = Gtk.ProgressBar.new()
18 | progress.set_text("Nothing Yet Happened")
19 | self.create_popup_menu(menu, progress)
20 | progress.set_pulse_step(0.05)
21 | eventbox.set_above_child(False)
22 | eventbox.connect("button_press_event", self.button_press_event, menu)
23 | eventbox.add(progress)
24 | self.add(eventbox)
25 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
26 | eventbox.realize()
27 |
28 | def create_popup_menu(self, menu, progress):
29 | pulse = Gtk.MenuItem.new_with_label("Pulse Progress")
30 | fill = Gtk.MenuItem.new_with_label("Set as Complete")
31 | clear = Gtk.MenuItem.new_with_label("Clear Progress")
32 | separator = Gtk.SeparatorMenuItem.new()
33 | pulse.connect("activate", self.pulse_activated, progress)
34 | fill.connect("activate", self.fill_activated, progress)
35 | clear.connect("activate", self.clear_activated, progress)
36 | menu.append(pulse)
37 | menu.append(separator)
38 | menu.append(fill)
39 | menu.append(clear)
40 | menu.attach_to_widget(progress, None)
41 | menu.show_all()
42 |
43 | def button_press_event(self, eventbox, event, menu):
44 | if event.button == 3 and event.type == Gdk.EventType.BUTTON_PRESS:
45 | menu.popup(None, None, None, None, event.button, event.time)
46 | return True
47 | return False
48 |
49 | def pulse_activated(self, item, progress):
50 | progress.pulse()
51 | progress.set_text("Pulse!")
52 |
53 | def fill_activated(self, item, progress):
54 | progress.set_fraction(1.0)
55 | progress.set_text("One Hundred Percent")
56 |
57 | def clear_activated(self, item, progress):
58 | progress.set_fraction(0.0)
59 | progress.set_text("Reset to Zero")
60 |
61 | class Application(Gtk.Application):
62 |
63 | def __init__(self, *args, **kwargs):
64 | super().__init__(*args, application_id="org.example.myapp",
65 | **kwargs)
66 | self.window = None
67 |
68 | def do_activate(self):
69 | if not self.window:
70 | self.window = AppWindow(application=self,
71 | title="Pop-up Menus")
72 | self.window.show_all()
73 | self.window.present()
74 |
75 | if __name__ == "__main__":
76 | app = Application()
77 | app.run(sys.argv)
78 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Exercise_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | # Create all of the necessary widgets and initialize the pop-up menu.
15 | menu = Gtk.Menu.new()
16 | eventbox = Gtk.EventBox.new()
17 | progress = Gtk.ProgressBar.new()
18 | progress.set_text("Nothing Yet Happened")
19 | progress.set_show_text(True)
20 | self.create_popup_menu(menu, progress)
21 | progress.set_pulse_step(0.05)
22 | eventbox.set_above_child(False)
23 | eventbox.connect("button_press_event", self.button_press_event, menu)
24 | eventbox.add(progress)
25 | self.add(eventbox)
26 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
27 | eventbox.realize()
28 |
29 | def create_popup_menu(self, menu, progress):
30 | pulse = Gtk.MenuItem.new_with_label("Pulse Progress")
31 | fill = Gtk.MenuItem.new_with_label("Set as Complete")
32 | clear = Gtk.MenuItem.new_with_label("Clear Progress")
33 | separator = Gtk.SeparatorMenuItem.new()
34 | pulse.connect("activate", self.pulse_activated, progress)
35 | fill.connect("activate", self.fill_activated, progress)
36 | clear.connect("activate", self.clear_activated, progress)
37 | menu.append(pulse)
38 | menu.append(separator)
39 | menu.append(fill)
40 | menu.append(clear)
41 | menu.attach_to_widget(progress, None)
42 | menu.show_all()
43 |
44 | def button_press_event(self, eventbox, event, menu):
45 | pass
46 |
47 | def pulse_activated(self, item, progress):
48 | pass
49 |
50 | def fill_activated(self, item, progress):
51 | pass
52 |
53 | def clear_activated(self, item, progress):
54 | pass
55 |
56 | def on_menu_cut(self, menuitem):
57 | pass
58 |
59 | def on_menu_copy(self, menuitem):
60 | pass
61 |
62 | def on_menu_paste(self, menuitem):
63 | pass
64 |
65 | class Application(Gtk.Application):
66 |
67 | def __init__(self, *args, **kwargs):
68 | super().__init__(*args, application_id="org.example.myapp",
69 | **kwargs)
70 | self.window = None
71 |
72 | def do_activate(self):
73 | if not self.window:
74 | self.window = AppWindow(application=self,
75 | title="Exercise 2")
76 | builder = Gtk.Builder()
77 | builder.add_from_file("./Exercise_2_Menubar.xml")
78 | self.set_menubar(builder.get_object("menubar"))
79 | self.window.show_all()
80 | self.window.present()
81 |
82 | def on_menu_new(self, menuitem):
83 | pass
84 |
85 | def on_menu_open(self, menuitem):
86 | pass
87 |
88 | def on_menu_save(self, menuitem):
89 | pass
90 |
91 |
92 | if __name__ == "__main__":
93 | app = Application()
94 | app.run(sys.argv)
95 |
--------------------------------------------------------------------------------
/Containers/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, 150)
14 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
15 | self.add(vbox)
16 |
17 | notebook = Gtk.Notebook.new()
18 | notebook.set_tab_pos(Gtk.PositionType.BOTTOM)
19 | vbox.pack_start(notebook, False, False, 5)
20 |
21 | label1 = Gtk.Label.new("Page 1")
22 | label2 = Gtk.Label.new("Page 2")
23 | label3 = Gtk.Label.new("Page 3")
24 | label4 = Gtk.Label.new("Page 4")
25 |
26 | button1 = Gtk.Button.new_with_label("Go to Page 2")
27 | button1.connect("clicked", self.on_notebook_button_clicked, notebook)
28 | button2 = Gtk.Button.new_with_label("Go to Page 3")
29 | button2.connect("clicked", self.on_notebook_button_clicked, notebook)
30 | button3 = Gtk.Button.new_with_label("Go to Page 4")
31 | button3.connect("clicked", self.on_notebook_button_clicked, notebook)
32 | button4 = Gtk.Button.new_with_label("Go to Page 1")
33 | button4.connect("clicked", self.on_notebook_button_clicked, notebook)
34 |
35 | page1 = notebook.append_page(button1, label1)
36 | page2 = notebook.append_page(button2, label2)
37 | page3 = notebook.append_page(button3, label3)
38 | page4 = notebook.append_page(button4, label4)
39 |
40 | buttonbox = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
41 | vbox.pack_start(buttonbox, False, False, 5)
42 | button_prev = Gtk.Button.new_with_label("Previous Page")
43 | button_prev.connect("clicked", self.on_button_prev_clicked, notebook)
44 | button_close = Gtk.Button.new_with_label("Close")
45 | button_close.connect("clicked", self.on_button_close_clicked)
46 | buttonbox.pack_end(button_prev, False, False, 5)
47 | buttonbox.pack_end(button_close, False, False, 5)
48 |
49 | def on_notebook_button_clicked(self, button, notebook):
50 | nextpage = notebook.props.page + 1
51 | if nextpage == 4:
52 | nextpage = 0
53 | notebook.set_current_page(nextpage)
54 |
55 | def on_button_prev_clicked(self, button, notebook):
56 | nextpage = notebook.props.page - 1
57 | if nextpage == -1:
58 | nextpage = 3
59 | notebook.set_current_page(nextpage)
60 |
61 | def on_button_close_clicked(self, button):
62 | self.destroy()
63 |
64 | class Application(Gtk.Application):
65 |
66 | def __init__(self, *args, **kwargs):
67 | super().__init__(*args, application_id="org.example.myapp",
68 | **kwargs)
69 | self.window = None
70 |
71 | def do_activate(self):
72 | if not self.window:
73 | self.window = AppWindow(application=self, title="Notebook")
74 | self.window.show_all()
75 | self.window.present()
76 |
77 | if __name__ == "__main__":
78 | app = Application()
79 | app.run(sys.argv)
80 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimpleToolbar.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
13 | toolbar = Gtk.Toolbar.new()
14 | entry = Gtk.Entry.new()
15 | vbox.pack_start(toolbar, True, False, 0)
16 | vbox.pack_start(entry, True, False, 0)
17 | self.create_toolbar(toolbar, entry)
18 | self.add(vbox)
19 | self.set_size_request(310, 75)
20 |
21 | def create_toolbar(self, toolbar, entry):
22 | icon_theme = Gtk.IconTheme.get_default()
23 | icon = icon_theme.load_icon("edit-cut", -1,
24 | Gtk.IconLookupFlags.FORCE_SIZE)
25 | image = Gtk.Image.new_from_pixbuf(icon)
26 | cut = Gtk.ToolButton.new(image, "Cut")
27 | icon = icon_theme.load_icon("edit-copy", -1,
28 | Gtk.IconLookupFlags.FORCE_SIZE)
29 | image = Gtk.Image.new_from_pixbuf(icon)
30 | copy = Gtk.ToolButton.new(image, "Copy")
31 | icon = icon_theme.load_icon("edit-paste", -1,
32 | Gtk.IconLookupFlags.FORCE_SIZE)
33 | image = Gtk.Image.new_from_pixbuf(icon)
34 | paste = Gtk.ToolButton.new(image, "Paste")
35 | icon = icon_theme.load_icon("edit-select-all", -1,
36 | Gtk.IconLookupFlags.FORCE_SIZE)
37 | image = Gtk.Image.new_from_pixbuf(icon)
38 | selectall = Gtk.ToolButton.new(image, "Select All")
39 | separator = Gtk.SeparatorToolItem.new()
40 | toolbar.set_show_arrow(True)
41 | toolbar.set_style(Gtk.ToolbarStyle.BOTH)
42 | toolbar.insert(cut, 0)
43 | toolbar.insert(copy, 1)
44 | toolbar.insert(paste, 2)
45 | toolbar.insert(separator, 3)
46 | toolbar.insert(selectall, 4)
47 | cut.connect("clicked", self.cut_clipboard, entry)
48 | copy.connect("clicked", self.copy_clipboard, entry)
49 | paste.connect("clicked", self.paste_clipboard, entry)
50 | selectall.connect("clicked", self.select_all, entry)
51 |
52 | def cut_clipboard(self, button, entry):
53 | entry.cut_clipboard()
54 |
55 | def copy_clipboard(self, button, entry):
56 | entry.copy_clipboard()
57 |
58 | def paste_clipboard(self, button, entry):
59 | entry.paste_clipboard()
60 |
61 | def select_all(self, button, entry):
62 | entry.select_region(0, -1)
63 |
64 | class Application(Gtk.Application):
65 |
66 | def __init__(self, *args, **kwargs):
67 | super().__init__(*args, application_id="org.example.myapp",
68 | **kwargs)
69 | self.window = None
70 |
71 | def do_activate(self):
72 | if not self.window:
73 | self.window = AppWindow(application=self,
74 | title="Toolbar")
75 | self.window.show_all()
76 | self.window.present()
77 |
78 | if __name__ == "__main__":
79 | app = Application()
80 | app.run(sys.argv)
81 |
--------------------------------------------------------------------------------
/Tree_View_Widget/GtkTreeView_GtkListStore4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | QUANTITY = 0
9 | PRODUCT = 1
10 |
11 | GroceryItem = (( 1, "Paper Towels" ),
12 | ( 2, "Bread" ),
13 | ( 1, "Butter" ),
14 | ( 1, "Milk" ),
15 | ( 3, "Chips" ),
16 | ( 4, "Soda" ))
17 |
18 | class AppWindow(Gtk.ApplicationWindow):
19 |
20 | def __init__(self, *args, **kwargs):
21 | super().__init__(*args, **kwargs)
22 | self.set_border_width(10)
23 | self.set_size_request(250, 175)
24 | treeview = Gtk.TreeView.new()
25 | self.setup_tree_view(treeview)
26 | store = Gtk.ListStore.new((GObject.TYPE_STRING,
27 | GObject.TYPE_STRING))
28 | for row in GroceryItem:
29 | iter = store.append(None)
30 | store.set(iter, QUANTITY, "%.0f" % row[QUANTITY], PRODUCT, row[PRODUCT])
31 | treeview.set_model(store)
32 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
33 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
34 | scrolled_win.add(treeview)
35 | self.add(scrolled_win)
36 |
37 | def setup_tree_view(self, treeview):
38 | # Create a GtkListStore that will be used for the combo box renderer.
39 | model = Gtk.ListStore.new((GObject.TYPE_STRING,
40 | GObject.TYPE_STRING))
41 | iter = model.append()
42 | model.set(iter, 0, "None")
43 | iter = model.append()
44 | model.set(iter, 0, "One")
45 | iter = model.append()
46 | model.set(iter, 0, "Half a Dozen")
47 | iter = model.append()
48 | model.set(iter, 0, "Dozen")
49 | iter = model.append()
50 | model.set(iter, 0, "Two Dozen")
51 | # Create the GtkCellRendererCombo and add the tree model. Then, add the
52 | # renderer to a new column and add the column to the GtkTreeView.
53 | renderer = Gtk.CellRendererCombo(text_column=0, editable=True,
54 | has_entry=True, model=model)
55 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
56 | treeview.append_column(column)
57 | renderer.connect("edited", self.cell_edited, treeview)
58 | renderer = Gtk.CellRendererText.new()
59 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
60 | treeview.append_column(column)
61 |
62 | def cell_edited(self, renderer, path, new_text, treeview):
63 | # Make sure the text is not empty. If not, apply it to the tree view cell.
64 | if new_text != "":
65 | model = treeview.get_model()
66 | iter = model.get_iter_from_string(path)
67 | if iter:
68 | model.set(iter, QUANTITY, new_text)
69 |
70 | class Application(Gtk.Application):
71 |
72 | def __init__(self, *args, **kwargs):
73 | super().__init__(*args, application_id="org.example.myapp",
74 | **kwargs)
75 | self.window = None
76 |
77 | def do_activate(self):
78 | if not self.window:
79 | self.window = AppWindow(application=self, title="Grocery List")
80 | self.window.show_all()
81 | self.window.present()
82 |
83 | if __name__ == "__main__":
84 | app = Application()
85 | app.run(sys.argv)
86 |
--------------------------------------------------------------------------------
/Tree_View_Widget/GtkTreeView_GtkTreeStore.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject
7 |
8 | BUY_IT = 0
9 | QUANTITY = 1
10 | PRODUCT = 2
11 |
12 | PRODUCT_CATEGORY = 0
13 | PRODUCT_CHILD = 1
14 |
15 | GroceryItem = (( PRODUCT_CATEGORY, True, 0, "Cleaning Supplies"),
16 | ( PRODUCT_CHILD, True, 1, "Paper Towels" ),
17 | ( PRODUCT_CHILD, True, 3, "Toilet Paper" ),
18 | ( PRODUCT_CATEGORY, True, 0, "Food"),
19 | ( PRODUCT_CHILD, True, 2, "Bread" ),
20 | ( PRODUCT_CHILD, False, 1, "Butter" ),
21 | ( PRODUCT_CHILD, True, 1, "Milk" ),
22 | ( PRODUCT_CHILD, False, 3, "Chips" ),
23 | ( PRODUCT_CHILD, True, 4, "Soda" ))
24 |
25 | class AppWindow(Gtk.ApplicationWindow):
26 |
27 | def __init__(self, *args, **kwargs):
28 | super().__init__(*args, **kwargs)
29 | self.set_border_width(10)
30 | self.set_size_request(275, 270)
31 | treeview = Gtk.TreeView.new()
32 | self.setup_tree_view(treeview)
33 | store = Gtk.TreeStore.new((GObject.TYPE_BOOLEAN,
34 | GObject.TYPE_INT,
35 | GObject.TYPE_STRING))
36 | iter = None
37 | i = 0
38 | for row in GroceryItem:
39 | (ptype, buy, quant, prod) = row
40 | if ptype == PRODUCT_CATEGORY:
41 | j = i + 1
42 | (ptype1, buy1, quant1, prod1) = GroceryItem[j]
43 | while j < len(GroceryItem) and ptype1 == PRODUCT_CHILD:
44 | if buy1:
45 | quant += quant1
46 | j += 1;
47 | if j < len(GroceryItem):
48 | (ptype1, buy1, quant1, prod1) = GroceryItem[j]
49 | iter = store.append(None)
50 | store.set(iter, BUY_IT, buy, QUANTITY, quant, PRODUCT, prod)
51 | else:
52 | child = store.append(iter)
53 | store.set(child, BUY_IT, buy, QUANTITY, quant, PRODUCT, prod)
54 | i += 1
55 | treeview.set_model(store)
56 | treeview.expand_all()
57 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
58 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
59 | scrolled_win.add(treeview)
60 | self.add(scrolled_win)
61 |
62 | def setup_tree_view(self, treeview):
63 | renderer = Gtk.CellRendererText.new()
64 | column = Gtk.TreeViewColumn("Buy", renderer, text=BUY_IT)
65 | treeview.append_column(column)
66 | renderer = Gtk.CellRendererText.new()
67 | column = Gtk.TreeViewColumn("Count", renderer, text=QUANTITY)
68 | treeview.append_column(column)
69 | renderer = Gtk.CellRendererText.new()
70 | column = Gtk.TreeViewColumn("Product", renderer, text=PRODUCT)
71 | treeview.append_column(column)
72 |
73 | class Application(Gtk.Application):
74 |
75 | def __init__(self, *args, **kwargs):
76 | super().__init__(*args, application_id="org.example.myapp",
77 | **kwargs)
78 | self.window = None
79 |
80 | def do_activate(self):
81 | if not self.window:
82 | self.window = AppWindow(application=self, title="Grocery List")
83 | self.window.show_all()
84 | self.window.present()
85 |
86 | if __name__ == "__main__":
87 | app = Application()
88 | app.run(sys.argv)
89 |
--------------------------------------------------------------------------------
/Tree_View_Widget/PixbufRenderers2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject, GdkPixbuf
7 |
8 | ICON = 0
9 | ICON_NAME = 1
10 |
11 | class AppWindow(Gtk.ApplicationWindow):
12 |
13 | def __init__(self, *args, **kwargs):
14 | super().__init__(*args, **kwargs)
15 | self.set_border_width(10)
16 | self.set_size_request(200, 175)
17 | treeview = Gtk.TreeView.new()
18 | self.setup_tree_view(treeview)
19 | store = Gtk.ListStore.new((GdkPixbuf.Pixbuf,
20 | GObject.TYPE_STRING))
21 | icon_theme = Gtk.IconTheme.get_default()
22 | iter = store.append(None)
23 | icon = icon_theme.load_icon("edit-cut", -1,
24 | Gtk.IconLookupFlags.FORCE_SIZE)
25 | store.set(iter, [ICON, ICON_NAME], [icon, "Cut"])
26 | iter = store.append(None)
27 | icon = icon_theme.load_icon("edit-copy", -1,
28 | Gtk.IconLookupFlags.FORCE_SIZE)
29 | store.set(iter, [ICON, ICON_NAME], [icon, "Copy"])
30 | iter = store.append(None)
31 | icon = icon_theme.load_icon("edit-paste", -1,
32 | Gtk.IconLookupFlags.FORCE_SIZE)
33 | store.set(iter, [ICON, ICON_NAME], [icon, "Paste"])
34 | iter = store.append(None)
35 | icon = icon_theme.load_icon("document-new", -1,
36 | Gtk.IconLookupFlags.FORCE_SIZE)
37 | store.set(iter, [ICON, ICON_NAME], [icon, "New"])
38 | iter = store.append(None)
39 | icon = icon_theme.load_icon("document-open", -1,
40 | Gtk.IconLookupFlags.FORCE_SIZE)
41 | store.set(iter, [ICON, ICON_NAME], [icon, "Open"])
42 | iter = store.append(None)
43 | icon = icon_theme.load_icon("document-print", -1,
44 | Gtk.IconLookupFlags.FORCE_SIZE)
45 | store.set(iter, [ICON, ICON_NAME], [icon, "Print"])
46 | treeview.set_model(store)
47 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
48 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
49 | scrolled_win.add(treeview)
50 | self.add(scrolled_win)
51 |
52 | def setup_tree_view(self, treeview):
53 | column = Gtk.TreeViewColumn.new()
54 | column.set_resizable(True)
55 | column.set_title("Some Items")
56 | renderer = Gtk.CellRendererPixbuf.new()
57 | # it is important to pack the renderer BEFORE adding attributes!!
58 | column.pack_start(renderer, False)
59 | column.add_attribute(renderer, "pixbuf", ICON)
60 | renderer = Gtk.CellRendererText.new()
61 | # it is important to pack the renderer BEFORE adding attributes!!
62 | column.pack_start(renderer, True)
63 | column.add_attribute(renderer, "text", ICON_NAME)
64 | treeview.append_column(column)
65 |
66 | class Application(Gtk.Application):
67 |
68 | def __init__(self, *args, **kwargs):
69 | super().__init__(*args, application_id="org.example.myapp",
70 | **kwargs)
71 | self.window = None
72 |
73 | def do_activate(self):
74 | if not self.window:
75 | self.window = AppWindow(application=self, title="Some Items")
76 | self.window.show_all()
77 | self.window.present()
78 |
79 | if __name__ == "__main__":
80 | app = Application()
81 | app.run(sys.argv)
82 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | # Create all of the necessary widgets and initialize the pop-up menu.
15 | menu = Gtk.Menu.new()
16 | eventbox = Gtk.EventBox.new()
17 | progress = Gtk.ProgressBar.new()
18 | progress.set_text("Nothing Yet Happened")
19 | progress.set_show_text(True)
20 | self.create_popup_menu(menu, progress)
21 | progress.set_pulse_step(0.05)
22 | eventbox.set_above_child(False)
23 | eventbox.connect("button_press_event", self.button_press_event, menu)
24 | eventbox.add(progress)
25 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
26 | eventbox.realize()
27 | self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
28 | self.hbox.pack_start(eventbox, False, False, 5)
29 | self.add(self.hbox)
30 |
31 | def create_popup_menu(self, menu, progress):
32 | pulse = Gtk.MenuItem.new_with_label("Pulse Progress")
33 | fill = Gtk.MenuItem.new_with_label("Set as Complete")
34 | clear = Gtk.MenuItem.new_with_label("Clear Progress")
35 | separator = Gtk.SeparatorMenuItem.new()
36 | pulse.connect("activate", self.pulse_activated, progress)
37 | fill.connect("activate", self.fill_activated, progress)
38 | clear.connect("activate", self.clear_activated, progress)
39 | menu.append(pulse)
40 | menu.append(separator)
41 | menu.append(fill)
42 | menu.append(clear)
43 | menu.attach_to_widget(progress, None)
44 | menu.show_all()
45 |
46 | def button_press_event(self, eventbox, event, menu):
47 | pass
48 |
49 | def pulse_activated(self, item, progress):
50 | pass
51 |
52 | def fill_activated(self, item, progress):
53 | pass
54 |
55 | def clear_activated(self, item, progress):
56 | pass
57 |
58 | def on_cutstandard(self, widget):
59 | pass
60 |
61 | def on_copystandard(self, widget):
62 | pass
63 |
64 | def on_pastestandard(self, widget):
65 | pass
66 |
67 |
68 | class Application(Gtk.Application):
69 |
70 | def __init__(self, *args, **kwargs):
71 | super().__init__(*args, application_id="org.example.myapp",
72 | **kwargs)
73 | self.window = None
74 |
75 | def do_activate(self):
76 | if not self.window:
77 | self.window = AppWindow(application=self,
78 | title="Exercise 1")
79 | builder = Gtk.Builder()
80 | builder.add_from_file("./Exercise_1_Toolbar.xml")
81 | builder.connect_signals(self.window)
82 | toolbar = builder.get_object("toolbar")
83 | toolbar.set_orientation(Gtk.Orientation.VERTICAL)
84 | self.window.hbox.pack_end(toolbar, True, False, 1)
85 | self.window.show_all()
86 | self.window.present()
87 |
88 | def on_newstandard(self, widget):
89 | pass
90 |
91 | def on_openstandard(self, widget):
92 | pass
93 |
94 | def on_savestandard(self, widget):
95 | pass
96 |
97 |
98 | if __name__ == "__main__":
99 | app = Application()
100 | app.run(sys.argv)
101 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimplePopupMenu3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(250, -1)
14 | # Create all of the necessary widgets and initialize the pop-up menu.
15 | menu = Gtk.Menu.new()
16 | eventbox = Gtk.EventBox.new()
17 | progress = Gtk.ProgressBar.new()
18 | progress.set_text("Nothing Yet Happened")
19 | progress.set_show_text(True)
20 | self.create_popup_menu(menu, progress)
21 | progress.set_pulse_step(0.05)
22 | eventbox.set_above_child(False)
23 | eventbox.connect("button_press_event", self.button_press_event, menu)
24 | eventbox.add(progress)
25 | self.add(eventbox)
26 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
27 | eventbox.realize()
28 |
29 | def create_popup_menu(self, menu, progress):
30 | group = Gtk.AccelGroup.new()
31 | self.add_accel_group(group)
32 | menu.set_accel_group(group)
33 | pulse = Gtk.MenuItem.new_with_label("Pulse Progress")
34 | fill = Gtk.MenuItem.new_with_label("Set as Complete")
35 | clear = Gtk.MenuItem.new_with_label("Clear Progress")
36 | separator = Gtk.SeparatorMenuItem.new()
37 | # Add the necessary keyboard accelerators.
38 | pulse.add_accelerator("activate", group, Gdk.KEY_P, Gdk.ModifierType.CONTROL_MASK,
39 | Gtk.AccelFlags.VISIBLE)
40 | fill.add_accelerator("activate", group, Gdk.KEY_F, Gdk.ModifierType.CONTROL_MASK,
41 | Gtk.AccelFlags.VISIBLE)
42 | clear.add_accelerator("activate", group, Gdk.KEY_C, Gdk.ModifierType.CONTROL_MASK,
43 | Gtk.AccelFlags.VISIBLE)
44 | pulse.connect("activate", self.pulse_activated, progress)
45 | fill.connect("activate", self.fill_activated, progress)
46 | clear.connect("activate", self.clear_activated, progress)
47 | menu.append(pulse)
48 | menu.append(separator)
49 | menu.append(fill)
50 | menu.append(clear)
51 | menu.attach_to_widget(progress, None)
52 | menu.show_all()
53 |
54 | def button_press_event(self, eventbox, event, menu):
55 | if event.button == 3 and event.type == Gdk.EventType.BUTTON_PRESS:
56 | menu.popup(None, None, None, None, event.button, event.time)
57 | return True
58 | return False
59 |
60 | def pulse_activated(self, item, progress):
61 | progress.pulse()
62 | progress.set_text("Pulse!")
63 |
64 | def fill_activated(self, item, progress):
65 | progress.set_fraction(1.0)
66 | progress.set_text("One Hundred Percent")
67 |
68 | def clear_activated(self, item, progress):
69 | progress.set_fraction(0.0)
70 | progress.set_text("Reset to Zero")
71 |
72 | class Application(Gtk.Application):
73 |
74 | def __init__(self, *args, **kwargs):
75 | super().__init__(*args, application_id="org.example.myapp",
76 | **kwargs)
77 | self.window = None
78 |
79 | def do_activate(self):
80 | if not self.window:
81 | self.window = AppWindow(application=self,
82 | title="Pop-up Menus")
83 | self.window.show_all()
84 | self.window.present()
85 |
86 | if __name__ == "__main__":
87 | app = Application()
88 | app.run(sys.argv)
89 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Exercise_1_Toolbar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | True
6 | False
7 |
8 |
9 | True
10 | False
11 | New Standard
12 | app.on_newstandard
13 | document-new
14 |
15 |
16 | False
17 | True
18 |
19 |
20 |
21 |
22 | True
23 | False
24 | Open Standard
25 | app.on_openstandard
26 | document-open
27 |
28 |
29 | False
30 | True
31 |
32 |
33 |
34 |
35 | True
36 | False
37 | Save Standard
38 | app.on_savestandard
39 | document-save
40 |
41 |
42 | False
43 | True
44 |
45 |
46 |
47 |
48 | True
49 | False
50 |
51 |
52 |
53 |
54 | True
55 | False
56 | Cut Standard
57 | win.on_cutstandard
58 | edit-cut
59 |
60 |
61 | False
62 | True
63 |
64 |
65 |
66 |
67 | True
68 | False
69 | Copy Standard
70 | win.on_copystandard
71 | edit-copy
72 |
73 |
74 | False
75 | True
76 |
77 |
78 |
79 |
80 | True
81 | False
82 | Paste Standard
83 | win.on_pastestandard
84 | edit-paste
85 |
86 |
87 | False
88 | True
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/More_Widgets/DrawingArea.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import cairo
5 | import gi
6 | gi.require_version('Gtk', '3.0')
7 | from gi.repository import Gtk, Gdk
8 |
9 | SIZE = 30
10 |
11 | class AppWindow(Gtk.ApplicationWindow):
12 |
13 | def __init__(self, *args, **kwargs):
14 | super().__init__(*args, **kwargs)
15 | self.set_size_request(450, 550)
16 | drawingarea = Gtk.DrawingArea()
17 | self.add(drawingarea)
18 | drawingarea.connect('draw', self.draw)
19 |
20 | def triangle(self, ctx):
21 | ctx.move_to(SIZE, 0)
22 | ctx.rel_line_to(SIZE, 2 * SIZE)
23 | ctx.rel_line_to(-2 * SIZE, 0)
24 | ctx.close_path()
25 |
26 | def square(self, ctx):
27 | ctx.move_to(0, 0)
28 | ctx.rel_line_to(2 * SIZE, 0)
29 | ctx.rel_line_to(0, 2 * SIZE)
30 | ctx.rel_line_to(-2 * SIZE, 0)
31 | ctx.close_path()
32 |
33 | def bowtie(self, ctx):
34 | ctx.move_to(0, 0)
35 | ctx.rel_line_to(2 * SIZE, 2 * SIZE)
36 | ctx.rel_line_to(-2 * SIZE, 0)
37 | ctx.rel_line_to(2 * SIZE, -2 * SIZE)
38 | ctx.close_path()
39 |
40 | def inf(self, ctx):
41 | ctx.move_to(0, SIZE)
42 | ctx.rel_curve_to(0, SIZE, SIZE, SIZE, 2 * SIZE, 0)
43 | ctx.rel_curve_to(SIZE, -SIZE, 2 * SIZE, -SIZE, 2 * SIZE, 0)
44 | ctx.rel_curve_to(0, SIZE, -SIZE, SIZE, -2 * SIZE, 0)
45 | ctx.rel_curve_to(-SIZE, -SIZE, -2 * SIZE, -SIZE, -2 * SIZE, 0)
46 | ctx.close_path()
47 |
48 | def draw_shapes(self, ctx, x, y, fill):
49 | ctx.save()
50 | ctx.new_path()
51 | ctx.translate(x + SIZE, y + SIZE)
52 | self.bowtie(ctx)
53 | if fill:
54 | ctx.fill()
55 | else:
56 | ctx.stroke()
57 | ctx.new_path()
58 | ctx.translate(3 * SIZE, 0)
59 | self.square(ctx)
60 | if fill:
61 | ctx.fill()
62 | else:
63 | ctx.stroke()
64 | ctx.new_path()
65 | ctx.translate(3 * SIZE, 0)
66 | self.triangle(ctx)
67 | if fill:
68 | ctx.fill()
69 | else:
70 | ctx.stroke()
71 | ctx.new_path()
72 | ctx.translate(3 * SIZE, 0)
73 | self.inf(ctx)
74 | if fill:
75 | ctx.fill()
76 | else:
77 | ctx.stroke()
78 | ctx.restore()
79 |
80 | def fill_shapes(self, ctx, x, y):
81 | self.draw_shapes(ctx, x, y, True)
82 |
83 | def stroke_shapes(self, ctx, x, y):
84 | self.draw_shapes(ctx, x, y, False)
85 |
86 | def draw(self, da, ctx):
87 | ctx.set_source_rgb(0, 0, 0)
88 | ctx.set_line_width(SIZE / 4)
89 | ctx.set_tolerance(0.1)
90 | ctx.set_line_join(cairo.LINE_JOIN_ROUND)
91 | ctx.set_dash([SIZE / 4.0, SIZE / 4.0], 0)
92 | self.stroke_shapes(ctx, 0, 0)
93 | ctx.set_dash([], 0)
94 | self.stroke_shapes(ctx, 0, 3 * SIZE)
95 | ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
96 | self.stroke_shapes(ctx, 0, 6 * SIZE)
97 | ctx.set_line_join(cairo.LINE_JOIN_MITER)
98 | self.stroke_shapes(ctx, 0, 9 * SIZE)
99 | self.fill_shapes(ctx, 0, 12 * SIZE)
100 | ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
101 | self.fill_shapes(ctx, 0, 15 * SIZE)
102 | ctx.set_source_rgb(1, 0, 0)
103 | self.stroke_shapes(ctx, 0, 15 * SIZE)
104 |
105 | class Application(Gtk.Application):
106 |
107 | def __init__(self, *args, **kwargs):
108 | super().__init__(*args, application_id="org.example.myapp",
109 | **kwargs)
110 | self.window = None
111 |
112 | def do_activate(self):
113 | if not self.window:
114 | self.window = AppWindow(application=self,
115 | title="Drawing Areas")
116 | self.window.show_all()
117 | self.window.present()
118 |
119 | if __name__ == "__main__":
120 | app = Application()
121 | app.run(sys.argv)
122 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/Exercise_2_Menubar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
91 |
92 |
--------------------------------------------------------------------------------
/Tree_View_Widget/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys, os
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, GObject, GdkPixbuf
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.ICON = 0
13 | self.FILENAME = 1
14 | self.current_path = []
15 | self.set_border_width(10)
16 | self.set_size_request(250, 500)
17 |
18 | treeview = Gtk.TreeView.new()
19 | treeview.connect("row-activated", self.on_row_activated)
20 |
21 | self.setup_tree_view(treeview)
22 | self.setup_tree_model(treeview)
23 |
24 | scrolled_win = Gtk.ScrolledWindow.new()
25 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC,
26 | Gtk.PolicyType.AUTOMATIC)
27 |
28 | scrolled_win.add(treeview)
29 | self.add(scrolled_win)
30 |
31 | def setup_tree_view(self, treeview):
32 | column = Gtk.TreeViewColumn.new()
33 | column.set_title("File Browser")
34 |
35 | renderer = Gtk.CellRendererPixbuf.new()
36 | column.pack_start(renderer, False)
37 | column.add_attribute(renderer, "pixbuf", self.ICON)
38 |
39 | renderer = Gtk.CellRendererText.new()
40 | column.pack_start(renderer, True)
41 | column.add_attribute(renderer, "text", self.FILENAME)
42 |
43 | treeview.append_column(column)
44 |
45 | def setup_tree_model(self, treeview):
46 | store = Gtk.ListStore(GdkPixbuf.Pixbuf, GObject.TYPE_STRING)
47 | treeview.set_model(store)
48 |
49 | self.populate_tree_model(treeview)
50 |
51 | def populate_tree_model(self, treeview):
52 | store = treeview.get_model()
53 | store.clear()
54 |
55 | # Build the tree path out of current_path.
56 | if self.current_path == []:
57 | location ="/"
58 | else:
59 | for temp in current_path:
60 | location = location + "/" + temp
61 |
62 | iter = store.append()
63 | store.set(iter, self.ICON, directory, self.FILENAME, "..")
64 |
65 | # Parse through the directory, adding all of its contents to the model.
66 | for file in os.listdir(location):
67 | temp = location + "/" + file
68 |
69 | if os.path.isdir(file):
70 | pixbuf = GdkPixbuf.Pixbuf.new_from_file ("directory.png")
71 | else:
72 | pixbuf = GdkPixbuf.Pixbuf.new_from_file ("file.png")
73 |
74 | iter = store.append()
75 | store.set(iter, self.ICON, pixbuf, self.FILENAME, file)
76 |
77 | def on_row_activated(self, treeview, fpath, column):
78 | model = treeview.get_model()
79 | iter = model.get_iter(fpath)
80 | if iter:
81 | file = model.get(iter, self.FILENAME)
82 |
83 | if file == "..":
84 | node = pop(current_path)
85 | self.populate_tree_model(treeview)
86 | else:
87 | if len(self.current_path) == 0:
88 | location = "/"
89 | else:
90 | if self.current_path == []:
91 | location ="/"
92 | else:
93 | for file in current_path:
94 | location = location + "/" + file
95 |
96 | iter = store.append()
97 | store.set(iter, self.ICON, directory, self.FILENAME, "..")
98 |
99 | if os.path.isdir(location):
100 | current_path = location
101 | self.populate_tree_model(treeview)
102 |
103 |
104 | class Application(Gtk.Application):
105 |
106 | def __init__(self, *args, **kwargs):
107 | super().__init__(*args, application_id="org.example.myapp",
108 | **kwargs)
109 | self.window = None
110 |
111 | def do_activate(self):
112 | if not self.window:
113 | self.window = AppWindow(application=self, title="Exercise 1")
114 | self.window.show_all()
115 | self.window.present()
116 |
117 | if __name__ == "__main__":
118 | app = Application()
119 | app.run(sys.argv)
120 |
--------------------------------------------------------------------------------
/Text_View_Widget/GtkTextBuffer_Formatted.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Pango
7 |
8 | text_to_scales = [("Quarter Sized", 0.25),
9 | ("Double Extra Small", 0.5787037037037),
10 | ("Extra Small", 0.6444444444444),
11 | ("Small", 0.8333333333333),
12 | ("Medium", 1.0), ("Large", 1.2),
13 | ("Extra Large", 1.4399999999999),
14 | ("Double Extra Large", 1.728),
15 | ("Double Sized", 2.0)]
16 |
17 | class AppWindow(Gtk.ApplicationWindow):
18 |
19 | def __init__(self, *args, **kwargs):
20 | super().__init__(*args, **kwargs)
21 | self.set_border_width(10)
22 | self.set_size_request(500, -1)
23 | textview = Gtk.TextView.new()
24 | buffer = textview.get_buffer()
25 | buffer.create_tag("bold", weight=Pango.Weight.BOLD)
26 | buffer.create_tag("italic", style=Pango.Style.ITALIC)
27 | buffer.create_tag("strike", strikethrough=True)
28 | buffer.create_tag("underline", underline=Pango.Underline.SINGLE)
29 | bold = Gtk.Button.new_with_label("Bold")
30 | italic = Gtk.Button.new_with_label("Italic")
31 | strike = Gtk.Button.new_with_label("Strike")
32 | underline = Gtk.Button.new_with_label("Underline")
33 | clear = Gtk.Button.new_with_label("Clear")
34 | scale_button = Gtk.ComboBoxText.new()
35 | i = 0
36 | while i < len(text_to_scales):
37 | (name, scale) = text_to_scales[i]
38 | scale_button.append_text(name)
39 | buffer.create_tag(tag_name=name, scale=scale)
40 | i += 1
41 | bold.__setattr__("tag", "bold")
42 | italic.__setattr__("tag", "italic")
43 | strike.__setattr__("tag", "strike")
44 | underline.__setattr__("tag", "underline")
45 | bold.connect("clicked", self.on_format, textview)
46 | italic.connect("clicked", self.on_format, textview)
47 | strike.connect("clicked", self.on_format, textview)
48 | underline.connect("clicked", self.on_format, textview)
49 | clear.connect("clicked", self.on_clear_clicked, textview)
50 | scale_button.connect("changed", self.on_scale_changed, textview)
51 | vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
52 | vbox.pack_start(bold, False, False, 0)
53 | vbox.pack_start(italic, False, False, 0)
54 | vbox.pack_start(strike, False, False, 0)
55 | vbox.pack_start(underline, False, False, 0)
56 | vbox.pack_start(scale_button, False, False, 0)
57 | vbox.pack_start(clear, False, False, 0)
58 | scrolled_win = Gtk.ScrolledWindow.new(None, None)
59 | scrolled_win.add(textview)
60 | scrolled_win.set_policy(Gtk.PolicyType.AUTOMATIC,
61 | Gtk.PolicyType.ALWAYS)
62 | hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
63 | hbox.pack_start(scrolled_win, True, True, 0)
64 | hbox.pack_start(vbox, False, True, 0)
65 | self.add(hbox)
66 |
67 | def on_format(self, button, textview):
68 | tagname = button.tag
69 | buffer = textview.get_buffer()
70 | (start, end) = buffer.get_selection_bounds()
71 | buffer.apply_tag_by_name(tagname, start, end)
72 |
73 | def on_scale_changed(self, button, textview):
74 | if button.get_active() == -1:
75 | return
76 | text = button.get_active_text()
77 | button.__setattr__("tag", text)
78 | self.on_format(button, textview)
79 | button.set_active(-1)
80 |
81 | def on_clear_clicked(self, button, textview):
82 | buffer = textview.get_buffer()
83 | (start, end) = buffer.get_selection_bounds()
84 | buffer.remove_all_tags(start, end)
85 |
86 | class Application(Gtk.Application):
87 |
88 | def __init__(self, *args, **kwargs):
89 | super().__init__(*args, application_id="org.example.myapp",
90 | **kwargs)
91 | self.window = None
92 |
93 | def do_activate(self):
94 | if not self.window:
95 | self.window = AppWindow(application=self, title="Text Tags")
96 | self.window.show_all()
97 | self.window.present()
98 |
99 | if __name__ == "__main__":
100 | app = Application()
101 | app.run(sys.argv)
102 |
--------------------------------------------------------------------------------
/Menus_And_Toolbars/SimplePopupMenu4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppMenuItem(Gtk.MenuItem):
9 | def __init__(self, *args, **kwargs):
10 | super().__init__(*args, **kwargs)
11 |
12 | def __setattr__(self, name, value):
13 | self.__dict__[name] = value
14 |
15 | def __getattr__(self, name):
16 | return self.__dict__[name]
17 |
18 | class AppWindow(Gtk.ApplicationWindow):
19 |
20 | def __init__(self, *args, **kwargs):
21 | super().__init__(*args, **kwargs)
22 | self.set_border_width(10)
23 | self.set_size_request(250, -1)
24 | # Create all of the necessary widgets and initialize the pop-up menu.
25 | menu = Gtk.Menu.new()
26 | eventbox = Gtk.EventBox.new()
27 | progress = Gtk.ProgressBar.new()
28 | progress.set_text("Nothing Yet Happened")
29 | progress.set_show_text(True)
30 | statusbar = Gtk.Statusbar.new()
31 | self.create_popup_menu(menu, progress, statusbar)
32 | progress.set_pulse_step(0.05)
33 | eventbox.set_above_child(False)
34 | eventbox.connect("button_press_event", self.button_press_event, menu)
35 | eventbox.add(progress)
36 | vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
37 | vbox.pack_start(eventbox, False, True, 0)
38 | vbox.pack_start(statusbar, False, True, 0)
39 | self.add(vbox)
40 | eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
41 | eventbox.realize()
42 |
43 | def create_popup_menu(self, menu, progress, statusbar):
44 | pulse = AppMenuItem(label="Pulse Progress")
45 | fill = AppMenuItem(label="Set as Complete")
46 | clear = AppMenuItem(label="Clear Progress")
47 | separator = Gtk.SeparatorMenuItem.new()
48 | pulse.connect("activate", self.pulse_activated, progress)
49 | fill.connect("activate", self.fill_activated, progress)
50 | clear.connect("activate", self.clear_activated, progress)
51 | # Connect signals to each menu item for status bar messages.
52 | pulse.connect("enter-notify-event", self.statusbar_hint, statusbar)
53 | pulse.connect("leave-notify-event", self.statusbar_hint, statusbar)
54 | fill.connect("enter-notify-event", self.statusbar_hint, statusbar)
55 | fill.connect("leave-notify-event", self.statusbar_hint, statusbar)
56 | clear.connect("enter-notify-event", self.statusbar_hint, statusbar)
57 | clear.connect("leave-notify-event", self.statusbar_hint, statusbar)
58 | pulse.__setattr__("menuhint", "Pulse the progress bar one step.")
59 | fill.__setattr__("menuhint", "Set the progress bar to 100%.")
60 | clear.__setattr__("menuhint", "Clear the progress bar to 0%.")
61 | menu.append(pulse)
62 | menu.append(separator)
63 | menu.append(fill)
64 | menu.append(clear)
65 | menu.attach_to_widget(progress, None)
66 | menu.show_all()
67 |
68 | def button_press_event(self, eventbox, event, menu):
69 | if event.button == 3 and event.type == Gdk.EventType.BUTTON_PRESS:
70 | menu.popup(None, None, None, None, event.button, event.time)
71 | return True
72 | return False
73 |
74 | def pulse_activated(self, item, progress):
75 | progress.pulse()
76 | progress.set_text("Pulse!")
77 |
78 | def fill_activated(self, item, progress):
79 | progress.set_fraction(1.0)
80 | progress.set_text("One Hundred Percent")
81 |
82 | def clear_activated(self, item, progress):
83 | progress.set_fraction(0.0)
84 | progress.set_text("Reset to Zero")
85 |
86 | def statusbar_hint(self, menuitem, event, statusbar):
87 | id = statusbar.get_context_id("MenuItemHints")
88 | if event.type == Gdk.EventType.ENTER_NOTIFY:
89 | hint = menuitem.__getattr__("menuhint")
90 | id = statusbar.push(id, hint)
91 | elif event.type == Gdk.EventType.LEAVE_NOTIFY:
92 | statusbar.pop(id)
93 | return False
94 |
95 | class Application(Gtk.Application):
96 |
97 | def __init__(self, *args, **kwargs):
98 | super().__init__(*args, application_id="org.example.myapp",
99 | **kwargs)
100 | self.window = None
101 |
102 | def do_activate(self):
103 | if not self.window:
104 | self.window = AppWindow(application=self,
105 | title="Pop-up Menus")
106 | self.window.show_all()
107 | self.window.present()
108 |
109 | if __name__ == "__main__":
110 | app = Application()
111 | app.run(sys.argv)
112 |
--------------------------------------------------------------------------------
/Dialogs/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 |
14 | savebutton = Gtk.Button.new_with_label("Save a File")
15 | createbutton = Gtk.Button.new_with_label("Create a New Folder")
16 | openbutton = Gtk.Button.new_with_label("Open One or More Files")
17 | selectbutton = Gtk.Button.new_with_label("Select a Folder")
18 |
19 | savebutton.connect("clicked", self.on_save_clicked)
20 | createbutton.connect("clicked", self.on_create_clicked)
21 | openbutton.connect("clicked", self.on_open_clicked)
22 | selectbutton.connect("clicked", self.on_select_clicked)
23 |
24 | vbox = Gtk.Box.new (Gtk.Orientation.VERTICAL, 5)
25 | vbox.pack_start(savebutton, False, False, 5)
26 | vbox.pack_start(createbutton, False, False, 5)
27 | vbox.pack_start(openbutton, False, False, 5)
28 | vbox.pack_start(selectbutton, False, False, 5)
29 |
30 | self.add (vbox)
31 |
32 | def on_save_clicked(self, button):
33 | dialog = Gtk.Dialog(title="Save File As ...",
34 | buttons=("Cancel", Gtk.ResponseType.CANCEL,
35 | "Save", Gtk.ResponseType.OK),
36 | parent=self)
37 | dialog.set_border_width(10)
38 | dialog.set_size_request(600, -1)
39 | chooser = Gtk.FileChooserWidget.new(Gtk.FileChooserAction.SAVE)
40 |
41 | dialog.vbox.pack_start(chooser, False, False, 5)
42 | dialog.show_all()
43 |
44 | result = dialog.run()
45 | if result == Gtk.ResponseType.OK:
46 | filename = chooser.get_filename()
47 | print("Saving file as: %s", filename)
48 |
49 | dialog.destroy()
50 |
51 | def on_create_clicked(self, button):
52 | dialog = Gtk.Dialog(title="Create a Folder",
53 | buttons=("Cancel", Gtk.ResponseType.CANCEL,
54 | "Create", Gtk.ResponseType.OK),
55 | parent=self)
56 | dialog.set_border_width(10)
57 | dialog.set_size_request(600, -1)
58 | chooser = Gtk.FileChooserWidget.new(Gtk.FileChooserAction.CREATE_FOLDER)
59 |
60 | dialog.vbox.pack_start(chooser, False, False, 5)
61 | dialog.show_all()
62 |
63 | result = dialog.run()
64 | if result == Gtk.ResponseType.OK:
65 | filename = chooser.get_filename()
66 | print("Creating directory: %s", filename)
67 |
68 | dialog.destroy()
69 |
70 |
71 | def on_open_clicked(self, button):
72 | dialog = Gtk.Dialog(title="Open file(s) ...",
73 | buttons=("Cancel", Gtk.ResponseType.CANCEL,
74 | "Open", Gtk.ResponseType.OK),
75 | parent=self)
76 | dialog.set_border_width(10)
77 | dialog.set_size_request(600, -1)
78 | chooser = Gtk.FileChooserWidget.new(Gtk.FileChooserAction.OPEN)
79 | chooser.set_select_multiple(True)
80 |
81 | dialog.vbox.pack_start(chooser, False, False, 5)
82 | dialog.show_all()
83 |
84 | result = dialog.run()
85 | if result == Gtk.ResponseType.OK:
86 | filenames = chooser.get_filenames()
87 | for filename in filenames:
88 | print("Open file: %s", filename)
89 |
90 | dialog.destroy()
91 |
92 |
93 | def on_select_clicked(self, button):
94 | dialog = Gtk.Dialog(title="Select Folder ...",
95 | buttons=("Cancel", Gtk.ResponseType.CANCEL,
96 | "Select", Gtk.ResponseType.OK),
97 | parent=self)
98 | dialog.set_border_width(10)
99 | dialog.set_size_request(600, -1)
100 | chooser = Gtk.FileChooserWidget.new(Gtk.FileChooserAction.SELECT_FOLDER)
101 |
102 | dialog.vbox.pack_start(chooser, False, False, 5)
103 | dialog.show_all()
104 |
105 | result = dialog.run()
106 | if result == Gtk.ResponseType.OK:
107 | filename = chooser.get_filename()
108 | print("Selected directory: %s", filename)
109 |
110 | dialog.destroy()
111 |
112 |
113 | class Application(Gtk.Application):
114 |
115 | def __init__(self, *args, **kwargs):
116 | super().__init__(*args, application_id="org.example.myapp",
117 | **kwargs)
118 | self.window = None
119 |
120 | def do_activate(self):
121 | if not self.window:
122 | self.window = AppWindow(application=self, title="Exercise 1")
123 | self.window.show_all()
124 | self.window.present()
125 |
126 | if __name__ == "__main__":
127 | app = Application()
128 | app.run(sys.argv)
129 |
--------------------------------------------------------------------------------
/App_and_AppWindow/Application2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import GLib, Gio, Gtk
7 |
8 | # This would typically be its own file
9 | MENU_XML="""
10 |
11 |
12 |
49 |
50 | """
51 |
52 | class AppWindow(Gtk.ApplicationWindow):
53 |
54 | def __init__(self, *args, **kwargs):
55 | super().__init__(*args, **kwargs)
56 | # This will be in the windows group and have the "win" prefix
57 | max_action = Gio.SimpleAction.new_stateful("maximize", None,
58 | GLib.Variant.new_boolean(False))
59 | max_action.connect("change-state", self.on_maximize_toggle)
60 | self.add_action(max_action)
61 | # Keep it in sync with the actual state
62 | self.connect("notify::is-maximized",
63 | lambda obj, pspec: max_action.set_state(
64 | GLib.Variant.new_boolean(obj.props.is_maximized)))
65 | lbl_variant = GLib.Variant.new_string("String 1")
66 | lbl_action = Gio.SimpleAction.new_stateful("change_label",
67 | lbl_variant.get_type(),
68 | lbl_variant)
69 | lbl_action.connect("change-state", self.on_change_label_state)
70 | self.add_action(lbl_action)
71 | self.label = Gtk.Label(label=lbl_variant.get_string(),
72 | margin=30)
73 | self.add(self.label)
74 |
75 | def on_change_label_state(self, action, value):
76 | action.set_state(value)
77 | self.label.set_text(value.get_string())
78 |
79 | def on_maximize_toggle(self, action, value):
80 | action.set_state(value)
81 | if value.get_boolean():
82 | self.maximize()
83 | else:
84 | self.unmaximize()
85 |
86 | class Application(Gtk.Application):
87 |
88 | def __init__(self, *args, **kwargs):
89 | super().__init__(*args, application_id="org.example.myapp",
90 | flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
91 | **kwargs)
92 | self.window = None
93 | self.add_main_option("test", ord("t"), GLib.OptionFlags.NONE,
94 | GLib.OptionArg.NONE, "Command line test", None)
95 |
96 | def do_startup(self):
97 | Gtk.Application.do_startup(self)
98 | action = Gio.SimpleAction.new("about", None)
99 | action.connect("activate", self.on_about)
100 | self.add_action(action)
101 | action = Gio.SimpleAction.new("quit", None)
102 | action.connect("activate", self.on_quit)
103 | self.add_action(action)
104 | builder = Gtk.Builder.new_from_string(MENU_XML, -1)
105 | self.set_app_menu(builder.get_object("app-menu"))
106 |
107 | def do_activate(self):
108 | # We only allow a single window and raise any existing ones
109 | if not self.window:
110 | # Windows are associated with the application
111 | # when the last one is closed the application shuts down
112 | self.window = AppWindow(application=self, title="Main Window")
113 | self.window.present()
114 |
115 | def do_command_line(self, command_line):
116 | options = command_line.get_options_dict()
117 | if options.contains("test"):
118 | # This is printed on the main instance
119 | print("Test argument recieved")
120 | self.activate()
121 | return 0
122 |
123 | def on_about(self, action, param):
124 | about_dialog = Gtk.AboutDialog(transient_for=self.window, modal=True)
125 | about_dialog.present()
126 |
127 | def on_quit(self, action, param):
128 | self.quit()
129 |
130 |
131 | if __name__ == "__main__":
132 | app = Application()
133 | app.run(sys.argv)
134 |
--------------------------------------------------------------------------------
/Dialogs/GtkAssistant.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 | import time
8 |
9 | class assistant(Gtk.Assistant):
10 | progress = None
11 |
12 | def __init__(self, *args, **kwargs):
13 | super().__init__(*args, **kwargs)
14 | self.set_size_request(450, 300)
15 | self.set_title("Gtk.Assistant Example")
16 | self.connect("destroy", Gtk.main_quit, None)
17 | # create page 0
18 | page0_widget = Gtk.Label("This in an example of a Gtk.Assistant. By\n" +
19 | "clicking the forward button, you can " +
20 | "continue\nto the next section!")
21 | self.append_page(page0_widget)
22 | self.set_page_title(page0_widget, "Introduction")
23 | self.set_page_type(page0_widget, Gtk.AssistantPageType.INTRO)
24 | self.set_page_complete(page0_widget, True)
25 | # create page 1
26 | page1_widget = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
27 | label = Gtk.Label("Your Name: ")
28 | entry = Gtk.Entry()
29 | page1_widget.pack_start(label, False, False, 5)
30 | page1_widget.pack_start(entry, False, False, 5)
31 | self.append_page(page1_widget)
32 | self.set_page_title(page1_widget, "")
33 | self.set_page_type(page1_widget, Gtk.AssistantPageType.CONTENT)
34 | self.set_page_complete(page1_widget, False)
35 | # create page 2
36 | page2_widget = Gtk.CheckButton.new_with_label("Click me to Continue!")
37 | self.append_page(page2_widget)
38 | self.set_page_title(page2_widget, "Click the Check Button")
39 | self.set_page_type(page2_widget, Gtk.AssistantPageType.CONTENT)
40 | self.set_page_complete(page2_widget, False)
41 | # create page 3
42 | page3_widget = Gtk.Alignment.new(0.5, 0.5, 0.0, 0.0)
43 | button = Gtk.Button.new_with_label("Click Me!")
44 | self.progress = Gtk.ProgressBar()
45 | hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
46 | hbox.pack_start(self.progress, True, False, 5)
47 | hbox.pack_start(button, False, False, 5)
48 | page3_widget.add(hbox)
49 | self.append_page(page3_widget)
50 | self.set_page_title(page3_widget, "Click the Check Button")
51 | self.set_page_type(page3_widget, Gtk.AssistantPageType.PROGRESS)
52 | self.set_page_complete(page3_widget, False)
53 | # create page 4
54 | page4_widget = Gtk.Label("Text has been entered in the label and the\n" +
55 | "combo box is clicked. If you are done, then\n" +
56 | "it is time to leave!")
57 | self.append_page(page4_widget)
58 | self.set_page_title(page4_widget, "Confirmation")
59 | self.set_page_type(page4_widget, Gtk.AssistantPageType.CONFIRM)
60 | self.set_page_complete(page4_widget, True)
61 | # set up the callbacks
62 | entry.connect("changed", self.entry_changed)
63 | page2_widget.connect("toggled", self.button_toggled)
64 | button.connect("clicked", self.button_clicked)
65 | self.connect("cancel", self.assistant_canceled)
66 | self.connect("close", self.assistant_close)
67 |
68 | def entry_changed(self, entry):
69 | text = entry.get_text()
70 | num = self.get_current_page()
71 | page = self.get_nth_page(num)
72 | self.set_page_complete(page, len(text) > 0)
73 |
74 | def button_toggled(self, toggle):
75 | active = toggle.get_active()
76 | self.set_page_complete(toggle, active)
77 |
78 | def button_clicked(self, button):
79 | percent = 0.0
80 | button.set_sensitive(False)
81 | page = self.get_nth_page(3)
82 | while (percent <= 100.0):
83 | message = str(percent) + " complete"
84 | print(message)
85 | self.progress.set_fraction(percent / 100.0)
86 | self.progress.set_text(message)
87 | while (Gtk.events_pending()):
88 | Gtk.main_iteration()
89 | time.sleep(1)
90 | percent += 5.0
91 | self.set_page_complete(page, True)
92 |
93 | def assistant_canceled(self, response):
94 | self.destroy()
95 |
96 | def assistant_close(self, response):
97 | print("You would apply your changes now!")
98 | self.destroy()
99 |
100 | class AppWindow(Gtk.ApplicationWindow):
101 | def __init__(self, *args, **kwargs):
102 | super().__init__(*args, **kwargs)
103 | self.set_border_width(25)
104 | button = Gtk.Button.new_with_mnemonic("_Open Assistant")
105 | button.connect("clicked", self.on_start_button_clicked)
106 | button.set_relief(Gtk.ReliefStyle.NORMAL)
107 | self.add(button)
108 | self.set_size_request(200, 100)
109 |
110 | def on_start_button_clicked(self, button):
111 | assistant()
112 |
113 | class Application(Gtk.Application):
114 |
115 | def __init__(self, *args, **kwargs):
116 | super().__init__(*args, application_id="org.example.myapp",
117 | **kwargs)
118 | self.window = None
119 |
120 | def do_activate(self):
121 | if not self.window:
122 | self.window = AppWindow(application=self, title="Gtk.Assistant")
123 | self.window.show_all()
124 | self.window.present()
125 |
126 | if __name__ == "__main__":
127 | app = Application()
128 | app.run(sys.argv)
129 |
--------------------------------------------------------------------------------
/More_Widgets/GtkPrintOperation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import math
5 | from os.path import expanduser
6 | import gi
7 | gi.require_version('Gtk', '3.0')
8 | gi.require_version('PangoCairo', '1.0')
9 | from gi.repository import Gtk, cairo, Pango, PangoCairo
10 |
11 | class Widgets:
12 |
13 | def __init__(self):
14 | self.window = None
15 | self.chooser = None
16 | self.data = None
17 | self.settings = Gtk.PrintSettings.new()
18 |
19 | class PrintData:
20 |
21 | def __init__(self):
22 | self.filename = None
23 | self.fontsize = None
24 | self.lines_per_page = None
25 | self.lines = None
26 | self.total_lines = None
27 | self.total_pages = None
28 |
29 |
30 | class AppWindow(Gtk.ApplicationWindow):
31 |
32 | def __init__(self, *args, **kwargs):
33 | super().__init__(*args, **kwargs)
34 | self.HEADER_HEIGHT = 20.0
35 | self.HEADER_GAP = 8.5
36 | w = Widgets()
37 | w.window = self
38 | self.set_border_width(10)
39 | w.chooser = Gtk.FileChooserButton.new ("Select a File",
40 | Gtk.FileChooserAction.OPEN)
41 | w.chooser.set_current_folder(expanduser("~"))
42 | print = Gtk.Button.new_with_label("Print")
43 | print.connect("clicked", self.print_file, w)
44 | hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
45 | hbox.pack_start(w.chooser, False, False, 0)
46 | hbox.pack_start(print, False, False, 0)
47 | self.add(hbox)
48 |
49 | def print_file(self, button, w):
50 | filename = w.chooser.get_filename()
51 | if filename == None:
52 | return
53 | operation = Gtk.PrintOperation.new()
54 | if w.settings != None:
55 | operation.set_print_settings(w.settings)
56 | w.data = PrintData()
57 | w.data.filename = filename
58 | w.data.font_size = 10.0
59 | operation.connect("begin_print", self.begin_print, w)
60 | operation.connect("draw_page", self.draw_page, w)
61 | operation.connect("end_print", self.end_print, w)
62 | res = operation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
63 | w.window)
64 | if res == Gtk.PrintOperationResult.APPLY:
65 | if w.settings != None:
66 | w.settings = None
67 | settings = operation.get_print_settings()
68 | elif res == Gtk.PrintOperationResult.ERROR:
69 | dialog = Gtk.MessageDialog.new(w.window,
70 | Gtk.DialogFlags.DESTROY_WITH_PARENT,
71 | Gtk.MessageType.ERROR,
72 | Gtk.ButtonsType.S_CLOSE,
73 | "Print operation error.")
74 | dialog.run()
75 | dialog.destroy()
76 |
77 | def begin_print(self, operation, context, w):
78 | w.data.lines = []
79 | f = open(w.data.filename)
80 | for line in f:
81 | w.data.lines.append(line)
82 | f.close()
83 | w.data.total_lines = len(w.data.lines)
84 | height = context.get_height() - self.HEADER_HEIGHT - self.HEADER_GAP
85 | w.data.lines_per_page = math.floor(height / (w.data.font_size + 3))
86 | w.data.total_pages = (w.data.total_lines - 1) / w.data.lines_per_page + 1
87 | operation.set_n_pages(w.data.total_pages)
88 |
89 | def draw_page(self, operation, context, page_nr, w):
90 | cr = context.get_cairo_context()
91 | width = context.get_width()
92 | layout = context.create_pango_layout()
93 | desc = Pango.font_description_from_string("Monospace")
94 | desc.set_size(w.data.font_size * Pango.SCALE)
95 | layout.set_font_description(desc)
96 | layout.set_text(w.data.filename, -1)
97 | layout.set_width(-1)
98 | layout.set_alignment(Pango.Alignment.LEFT)
99 | (width, height) = layout.get_size()
100 | text_height = height / Pango.SCALE
101 | cr.move_to(0, (self.HEADER_HEIGHT - text_height) / 2)
102 | PangoCairo.show_layout(cr, layout)
103 | page_str = "%d of %d" % (page_nr + 1, w.data.total_pages)
104 | layout.set_text(page_str, -1)
105 | (width, height) = layout.get_size()
106 | layout.set_alignment(Pango.Alignment.RIGHT)
107 | cr.move_to(width - (width / Pango.SCALE),
108 | (self.HEADER_HEIGHT - text_height) / 2)
109 | PangoCairo.show_layout(cr, layout)
110 | cr.move_to(0, self.HEADER_HEIGHT + self.HEADER_GAP)
111 | line = page_nr * w.data.lines_per_page
112 | #for (i = 0; i < w.data.lines_per_page && line < w.data.total_lines; i++)
113 | i = 0
114 | while i < w.data.lines_per_page and line < w.data.total_lines:
115 | layout.set_text(w.data.lines[line], -1)
116 | PangoCairo.show_layout(cr, layout)
117 | cr.rel_move_to(0, w.data.font_size + 3)
118 | line += 1
119 | i += 1
120 |
121 | def end_print(self, operation, context, w):
122 | w.data.lines = None
123 | w.data = None
124 |
125 | class Application(Gtk.Application):
126 |
127 | def __init__(self, *args, **kwargs):
128 | super().__init__(*args, application_id="org.example.myapp",
129 | **kwargs)
130 | self.window = None
131 |
132 | def do_activate(self):
133 | if not self.window:
134 | self.window = AppWindow(application=self,
135 | title="Calendar")
136 | self.window.show_all()
137 | self.window.present()
138 |
139 | if __name__ == "__main__":
140 | app = Application()
141 | app.run(sys.argv)
142 |
--------------------------------------------------------------------------------
/Custom_Widgets/Multi_Thread.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys, threading, queue, time
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk
7 |
8 |
9 | def dbsim(q1, q2):
10 | while True:
11 | data = q1.get()
12 | # the request is always the same for our purpose
13 | items = {'lname':"Bunny", 'fname':"Bugs",
14 | 'street':"Termite Terrace", 'city':"Hollywood",
15 | 'state':"California", 'zip':"99999",
16 | 'employer':"Warner Bros.", 'position':"Cartoon character",
17 | 'credits':"Rabbit Hood, Haredevil Hare, What's Up Doc?"}
18 | q2.put(items)
19 | q1.task_done()
20 |
21 |
22 | class AppWindow(Gtk.ApplicationWindow):
23 |
24 | def __init__(self, *args, **kwargs):
25 | super().__init__(*args, **kwargs)
26 | self.lname = None
27 | self.fname = None
28 | self.street = None
29 | self.city = None
30 | self.state = None
31 | self.zip = None
32 | self.employer = None
33 | self.position = None
34 | self.credits = None
35 | self.q1 = queue.Queue()
36 | self.q2 = queue.Queue()
37 | self.thrd = threading.Thread(target=dbsim, daemon=True, args=(self.q1, self.q2))
38 | self.thrd.start()
39 |
40 | # window setup
41 | self.set_border_width(10)
42 | grid = Gtk.Grid.new()
43 | grid.set_column_spacing(5)
44 | grid.set_row_spacing(5)
45 | # name
46 | label = Gtk.Label.new("Last name:")
47 | label.set_halign(Gtk.Align.END)
48 | grid.attach(label, 0, 0, 1, 1)
49 | self.lname = Gtk.Entry.new()
50 | grid.attach(self.lname, 1, 0, 1, 1)
51 | label = Gtk.Label.new("First name:")
52 | label.set_halign(Gtk.Align.END)
53 | grid.attach(label, 2, 0, 1, 1)
54 | self.fname = Gtk.Entry.new()
55 | grid.attach(self.fname, 3, 0, 1, 1)
56 | # address
57 | label = Gtk.Label.new("Street:")
58 | label.set_halign(Gtk.Align.END)
59 | grid.attach(label, 0, 1, 1, 1)
60 | self.street = Gtk.Entry.new()
61 | grid.attach(self.street, 1, 1, 1, 1)
62 | label = Gtk.Label.new("City:")
63 | label.set_halign(Gtk.Align.END)
64 | grid.attach(label, 2, 1, 1, 1)
65 | self.city = Gtk.Entry.new()
66 | grid.attach(self.city, 3, 1, 1, 1)
67 | label = Gtk.Label.new("State:")
68 | label.set_halign(Gtk.Align.END)
69 | grid.attach(label, 0, 2, 1, 1)
70 | self.state = Gtk.Entry.new()
71 | grid.attach(self.state, 1, 2, 1, 1)
72 | label = Gtk.Label.new("Zip:")
73 | label.set_halign(Gtk.Align.END)
74 | grid.attach(label, 2, 2, 1, 1)
75 | self.zip = Gtk.Entry.new()
76 | grid.attach(self.zip, 3, 2, 1, 1)
77 | # employment status
78 | label = Gtk.Label.new("Employer:")
79 | label.set_halign(Gtk.Align.END)
80 | grid.attach(label, 0, 3, 1, 1)
81 | self.employer = Gtk.Entry.new()
82 | grid.attach(self.employer, 1, 3, 1, 1)
83 | label = Gtk.Label.new("Position:")
84 | label.set_halign(Gtk.Align.END)
85 | grid.attach(label, 2, 3, 1, 1)
86 | self.position = Gtk.Entry.new()
87 | grid.attach(self.position, 3, 3, 1, 1)
88 | label = Gtk.Label.new("Credits:")
89 | label.set_halign(Gtk.Align.END)
90 | grid.attach(label, 0, 4, 1, 1)
91 | self.credits = Gtk.Entry.new()
92 | grid.attach(self.credits, 1, 4, 3, 1)
93 | # buttons
94 | bb = Gtk.ButtonBox(Gtk.Orientation.HORIZONTAL)
95 | load_button = Gtk.Button.new_with_label("Load")
96 | bb.pack_end(load_button, False, False, 0)
97 | load_button.connect("clicked", self.on_load_button_clicked)
98 | save_button = Gtk.Button.new_with_label("Save")
99 | bb.pack_end(save_button, False, False, 0)
100 | save_button.connect("clicked", self.on_save_button_clicked)
101 | cancel_button = Gtk.Button.new_with_label("Cancel")
102 | bb.pack_end(cancel_button, False, False, 0)
103 | cancel_button.connect("clicked", self.on_cancel_button_clicked)
104 | # box setup
105 | vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=5)
106 | vbox.add(grid)
107 | vbox.add(bb)
108 | self.add(vbox)
109 |
110 | def on_cancel_button_clicked(self, button):
111 | self.destroy()
112 |
113 | def on_load_button_clicked(self, button):
114 | self.q1.put('request')
115 | # wait for the results to be queued
116 | data = None
117 | while Gtk.events_pending() or data == None:
118 | Gtk.main_iteration()
119 | try:
120 | data = self.q2.get(block=False)
121 | except queue.Empty:
122 | continue
123 | self.lname.set_text(data['lname'])
124 | self.fname.set_text(data['fname'])
125 | self.street.set_text(data['street'])
126 | self.city.set_text(data['city'])
127 | self.state.set_text(data['state'])
128 | self.zip.set_text(data['zip'])
129 | self.employer.set_text(data['employer'])
130 | self.position.set_text(data['position'])
131 | self.credits.set_text(data['credits'])
132 | self.q2.task_done()
133 |
134 | def on_save_button_clicked(self, button):
135 | self.lname.set_text("")
136 | self.fname.set_text("")
137 | self.street.set_text("")
138 | self.city.set_text("")
139 | self.state.set_text("")
140 | self.zip.set_text("")
141 | self.employer.set_text("")
142 | self.position.set_text("")
143 | self.credits.set_text("")
144 |
145 |
146 | class Application(Gtk.Application):
147 |
148 | def __init__(self, *args, **kwargs):
149 | super().__init__(*args, application_id="org.example.myapp",
150 | **kwargs)
151 | self.window = None
152 |
153 | def do_activate(self):
154 | if not self.window:
155 | self.window = AppWindow(application=self,
156 | title="Multi-Thread")
157 | self.window.show_all()
158 | self.window.present()
159 |
160 | if __name__ == "__main__":
161 | app = Application()
162 | app.run(sys.argv)
163 |
--------------------------------------------------------------------------------
/Integrating/Calculator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import math
5 | import gi
6 | gi.require_version('Gtk', '3.0')
7 | from gi.repository import Gtk, Pango
8 |
9 |
10 |
11 | class SignalHandlers():
12 |
13 | def __init__(self, builder):
14 | self.builder = builder
15 | self.entry = None
16 | self.OP_NULL = 0
17 | self.OP_ADD = 1
18 | self.OP_SUBTRACT = 2
19 | self.OP_MULTIPLY = 3
20 | self.OP_DIVIDE = 4
21 | self.OP_POWER = 5
22 | self.clear_value = False
23 | self.value_set = False
24 | self.prev_value = 0
25 | self.pending_op = self.OP_NULL
26 |
27 | entry = builder.get_object("output")
28 | self.entry = entry
29 | fd = Pango.font_description_from_string("Monospace Bold 16")
30 | entry.set_text("0")
31 | entry.modify_font(fd)
32 |
33 | # Set user data for the operators and decimal buttons.
34 | add = builder.get_object("add")
35 | add.operator = self.OP_ADD
36 | sub = builder.get_object("sub")
37 | sub.operator = self.OP_SUBTRACT
38 | mul = builder.get_object("mul")
39 | mul.operator = self.OP_MULTIPLY
40 | div = builder.get_object("div")
41 | div.operator = self.OP_DIVIDE
42 | power = builder.get_object("power")
43 | power.operator = self.OP_POWER
44 | decimal = builder.get_object("decimal")
45 | decimal.number = 10
46 |
47 | # Set the user data for the number buttons.
48 | for i in range(0, 10):
49 | name = "num_%i" % (i,)
50 | num = builder.get_object(name)
51 | num.number = i
52 |
53 | def do_operation(self, entry, value):
54 | # Perform the specified operation, either add, subtract, multiply,
55 | # divide, or the power operation.
56 |
57 | # Perform the operation on prev_value with the new value and store
58 | # the result back into prev_value.
59 | if self.pending_op == self.OP_ADD:
60 | self.prev_value += value
61 | elif self.pending_op == self.OP_SUBTRACT:
62 | self.prev_value -= value
63 | elif self.pending_op == self.OP_MULTIPLY:
64 | self.prev_value *= value
65 | elif self.pending_op == self.OP_DIVIDE:
66 | self.prev_value /= value;
67 | elif self.pending_op == self.OP_POWER:
68 | self.prev_value = pow(prev_value, value)
69 | else:
70 | return
71 |
72 | # Reset the pending operation and create a string with the new value.
73 | self.pending_op = self.OP_NULL
74 | entry.set_text(self.format_num(self.prev_value))
75 |
76 | def on_num_clicked(self, button):
77 | # Retrieve the number that is stored in user data.
78 | num = button.number
79 |
80 | # Clear the value if a new number should be entered.
81 | if self.clear_value:
82 | self.entry.set_text("0")
83 | self.clear_value = False
84 |
85 | # Append a decimal place to the GtkEntry. Make sure to keep track of
86 | # whether the decimal place was already entered.
87 | text = self.entry.get_text()
88 | if (num == 10):
89 | if len(text) > 9:
90 | return
91 | elif text.find('.') >= 0:
92 | return
93 | else:
94 | text = text + '.'
95 | # Append a number place to the GtkEntry if the length is less than 10.
96 | else:
97 | text = text + str(num)
98 | if len(text) > 10:
99 | return
100 | # Remove preceeding zeros.
101 | text = text.lstrip('0')
102 | self.entry.set_text(text)
103 |
104 | def on_equal_clicked(self, button):
105 | # Perform any pending operations because the equal button was pressed.
106 | value = float(self.entry.get_text())
107 |
108 | self.do_operation(self.entry, value)
109 | self.clear_value = True
110 | self.value_set = False
111 |
112 | def on_op_clicked(self, button):
113 | op = button.operator
114 | value = float(self.entry.get_text())
115 |
116 | # Perform any pending operations and then store the new operation.
117 | self.do_operation(self.entry, value)
118 | self.pending_op = op;
119 | self.clear_value = True
120 |
121 | # Set the current value as the previous value if it should be
122 | # overwritten.
123 | if not self.value_set:
124 | self.prev_value = value;
125 | self.value_set = True
126 |
127 | def on_sign_clicked(self, button):
128 | value = float(self.entry.get_text())
129 |
130 | # You cannot negate a value of zero.
131 | if value == 0.0:
132 | return
133 | value *= -1
134 |
135 | self.entry.set_text(self.format_num(value))
136 |
137 | def on_sqrt_clicked(self, button):
138 | # Take the square root of the current value.
139 | value = math.sqrt(float(self.entry.get_text()))
140 |
141 | self.entry.set_text(self.format_num(value))
142 |
143 | def on_clear_clicked(self, button):
144 | self.entry.set_text("0")
145 |
146 | self.clear_value = False
147 | self.value_set = False
148 | self.prev_value = 0
149 | self.pending_op = self.OP_NULL
150 |
151 | def format_num(self, num):
152 | text = str(num)
153 | text = text.rstrip('0')
154 | text = text.lstrip('0')
155 | text = text.rstrip('.') # remove trailing decimal
156 | return text
157 |
158 | class Application(Gtk.Application):
159 |
160 | def __init__(self, *args, **kwargs):
161 | super().__init__(*args, application_id="org.example.myapp",
162 | **kwargs)
163 | self.window = None
164 | self.builder = None
165 |
166 | def do_activate(self):
167 | if not self.window:
168 | self.builder = Gtk.Builder()
169 | self.builder.add_from_file("./Calculator.glade")
170 | self.window = self.builder.get_object("window")
171 | self.builder.connect_signals(SignalHandlers(self.builder))
172 | self.add_window(self.window)
173 | self.window.show_all()
174 |
175 | if __name__ == "__main__":
176 | app = Application()
177 | app.run(sys.argv)
178 |
179 |
--------------------------------------------------------------------------------
/Text_View_Widget/Exercise_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import sys
4 | import gi
5 | gi.require_version('Gtk', '3.0')
6 | from gi.repository import Gtk, Gdk
7 |
8 | class AppWindow(Gtk.ApplicationWindow):
9 |
10 | def __init__(self, *args, **kwargs):
11 | super().__init__(*args, **kwargs)
12 | self.set_border_width(10)
13 | self.set_size_request(300, -1)
14 |
15 | textview = Gtk.TextView.new()
16 | search = Gtk.Entry.new()
17 | search.set_text("Search for ...")
18 |
19 | new = Gtk.Button.new_with_label("New")
20 | openb = Gtk.Button.new_with_label("Open")
21 | save = Gtk.Button.new_with_label("Save")
22 | cut = Gtk.Button.new_with_label("Cut")
23 | copy = Gtk.Button.new_with_label("Copy")
24 | paste = Gtk.Button.new_with_label("Paste")
25 | find = Gtk.Button.new_with_label("Find")
26 |
27 | new.connect("clicked", self.on_new_clicked, textview)
28 | openb.connect("clicked", self.on_open_clicked, textview)
29 | save.connect("clicked", self.on_save_clicked, textview)
30 | cut.connect("clicked", self.on_cut_clicked, textview)
31 | copy.connect("clicked", self.on_copy_clicked, textview)
32 | paste.connect("clicked", self.on_paste_clicked, textview)
33 | find.connect("clicked", self.on_find_clicked, textview, search)
34 |
35 | scrolled_win = Gtk.ScrolledWindow.new()
36 | scrolled_win.add(textview)
37 |
38 | vbox1 = Gtk.Box.new (Gtk.Orientation.VERTICAL, 5)
39 | vbox1.pack_start(new, False, False, 0)
40 | vbox1.pack_start(openb, False, False, 0)
41 | vbox1.pack_start(save, False, False, 0)
42 | vbox1.pack_start(cut, False, False, 0)
43 | vbox1.pack_start(copy, False, False, 0)
44 | vbox1.pack_start(paste, False, False, 0)
45 |
46 | searchbar = Gtk.Box.new (Gtk.Orientation.HORIZONTAL, 5)
47 | searchbar.pack_start(search, False, False, 0)
48 | searchbar.pack_start(find, False, False, 0)
49 |
50 | hbox1 = Gtk.Box.new (Gtk.Orientation.HORIZONTAL, 5)
51 | hbox1.pack_start(scrolled_win, True, True, 0)
52 | hbox1.pack_start(vbox1, False, False, 0)
53 |
54 | vbox2 = Gtk.Box.new (Gtk.Orientation.VERTICAL, 5)
55 | vbox2.pack_start(hbox1, True, True, 0)
56 | vbox2.pack_start(searchbar, False, False, 0)
57 |
58 | self.add(vbox2)
59 | self.show_all()
60 |
61 | def on_new_clicked(self, button, textview):
62 | dialog = Gtk.MessageDialog(title="Question", parent=self,
63 | flags=Gtk.DialogFlags.MODAL)
64 | dialog.set_border_width(10)
65 | dialog.add_button("Yes", Gtk.ResponseType.YES)
66 | dialog.add_button("No", Gtk.ResponseType.NO)
67 | dialog.props.text = "All changes will be lost.\nDo you want to continue?"
68 | dialog.show_all()
69 | response = dialog.run()
70 | if response == Gtk.ResponseType.YES:
71 | buffer = textview.get_buffer()
72 | buffer.set_text("")
73 | dialog.destroy()
74 |
75 | def on_open_clicked(self, button, textview):
76 | dialog = Gtk.FileChooserDialog(title="Choose a file ..",
77 | parent=self,
78 | flags=Gtk.FileChooserAction.OPEN,
79 | buttons=("Open", Gtk.ResponseType.APPLY,
80 | "Cancel", Gtk.ResponseType.CANCEL))
81 | dialog.show_all()
82 | response = dialog.run()
83 | if response == Gtk.ResponseType.APPLY:
84 | buffer = textview.get_buffer()
85 | file = dialog.get_filename()
86 | f = open(file, 'r')
87 | content = f.read()
88 | f.close()
89 | buffer.set_text(content)
90 | dialog.destroy()
91 |
92 | def on_save_clicked(self, button, textview):
93 | dialog = Gtk.FileChooserDialog(title="Save the file ..",
94 | parent=self,
95 | flags=Gtk.FileChooserAction.SAVE,
96 | buttons=("Save", Gtk.ResponseType.APPLY,
97 | "Cancel", Gtk.ResponseType.CANCEL))
98 | response = dialog.run()
99 | if response == Gtk.ResponseType.APPLY:
100 | file = dialog.get_filename()
101 | buffer = textview.get_buffer()
102 | (start, end) = buffer.get_bounds()
103 | content = buffer.get_text(start, end, True)
104 | f = open(file, 'w')
105 | f.write(content)
106 | f.close()
107 | dialog.destroy()
108 |
109 | def on_cut_clicked(self, button, textview):
110 | clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
111 | buffer = textview.get_buffer()
112 | buffer.cut_clipboard(clipboard, True)
113 |
114 | def on_copy_clicked(self, button, textview):
115 | clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
116 | buffer = textview.get_buffer()
117 | buffer.copy_clipboard(clipboard)
118 |
119 | def on_paste_clicked(self, button, textview):
120 | clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
121 | buffer = textview.get_buffer()
122 | buffer.paste_clipboard(clipboard, None, True)
123 |
124 | def on_find_clicked(self, button, textview, search):
125 | find = search.get_text()
126 | buffer = textview.get_buffer()
127 | cursorpos = buffer.props.cursor_position
128 | start = buffer.get_iter_at_offset(cursorpos)
129 | end = buffer.get_iter_at_offset(-1)
130 | if start.compare(end) != 0:
131 | start.forward_char()
132 | success = start.forward_search(find, 0, None)
133 | if success != None and len(success) != 0:
134 | (start, end) = success
135 | mark = buffer.create_mark(None, start, False)
136 | textview.scroll_mark_onscreen(mark)
137 | buffer.delete_mark(mark)
138 | buffer.select_range(start, end)
139 | else:
140 | dialog = Gtk.MessageDialog(title="Information", parent=self,
141 | flags=Gtk.DialogFlags.MODAL)
142 | dialog.set_border_width(10)
143 | dialog.add_button("Ok", Gtk.ResponseType.OK)
144 | dialog.props.text = "The text was not found!"
145 | dialog.show_all()
146 | dialog.run()
147 | dialog.destroy()
148 |
149 |
150 | class Application(Gtk.Application):
151 |
152 | def __init__(self, *args, **kwargs):
153 | super().__init__(*args, application_id="org.example.myapp",
154 | **kwargs)
155 | self.window = None
156 |
157 | def do_activate(self):
158 | if not self.window:
159 | self.window = AppWindow(application=self, title="Exercise 1")
160 | self.window.show_all()
161 | self.window.present()
162 |
163 | if __name__ == "__main__":
164 | app = Application()
165 | app.run(sys.argv)
166 |
--------------------------------------------------------------------------------