├── .gitignore ├── Box_LAYOUT ├── README.md └── Screenshot.png ├── README.md ├── appchooserbutton ├── README.md └── Screenshot.png ├── applicationwindow ├── README.md └── Screenshot_1.png ├── button ├── README.md └── Screenshot.png ├── checkbutton ├── README.md └── Screenshot.png ├── colorbutton ├── README.md └── Screenshot.png ├── comboboxtext ├── README.md └── Screenshot.png ├── entry ├── README.md └── Screenshot.png ├── gio_settings ├── README.md └── Screenshot1.png ├── headerbar_and_menubutton ├── README.md └── Screenshot.png ├── infobar ├── README.md └── Screenshot.png ├── label ├── README.md └── Screenshot.png ├── libadwaita_scale_clamp_expanderrow ├── README.md └── Screenshot_1.png ├── libadwaita_scale_clamp_expanderrow_searchbar ├── README.md └── Screenshot_1.png ├── linkbutton ├── README.md └── Screenshot.png ├── listbox_searchbar ├── README.md └── Screenshot.png ├── passwordentry ├── README.md └── Screenshot.png ├── progressbar ├── README.md └── Screenshot.png ├── simple_list_view_example ├── README.md └── Screenshot.png ├── small_programs ├── pyrandompics │ ├── LICENSE │ ├── README.md │ ├── Screenshot.png │ ├── Screenshot1.png │ ├── Screenshot2.png │ ├── Screenshot3.png │ └── pyrandompics.py ├── pyscanbc │ ├── README.md │ ├── Screenshot.png │ ├── Screenshot1.png │ └── pyscanbc.py └── timer │ ├── README.md │ ├── Screenshot.png │ ├── Screenshot1.png │ └── timer.py ├── spinner ├── README.md └── Screenshot.png ├── stack ├── README.md └── Screenshot.png ├── stack_flowbox_css_provider ├── README.md ├── Screenshot.png └── icons_folder │ ├── Blender-icon.png │ ├── Chromium_logo.png │ ├── Opera-logo-256x256.png │ ├── appicns_Firefox.png │ ├── brave.png │ ├── gimp.png │ ├── inkscape.png │ ├── kdenlive.png │ ├── krita.png │ └── vivaldi.png ├── switch ├── README.md └── Screenshot.png ├── togglebutton ├── README.md └── Screenshot.png ├── volumebutton ├── README.md └── Screenshot.png └── window ├── README.md └── Screenshot_1.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Box_LAYOUT/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Box 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 15 | self.set_child(self.main_vertical_box) 16 | 17 | self.about_button = Gtk.Button.new() 18 | self.about_button.set_label("About") # Or Change "label Propertie" self.about_button.props.label = "About" 19 | self.about_button.connect("clicked",self.on_about_button_clicked,"My Example App") 20 | self.main_vertical_box.append(self.about_button) 21 | 22 | self.quit_button = Gtk.Button.new_with_label("Quit") 23 | self.quit_button.connect("clicked",self.on_quit_button_clicked) 24 | self.quit_button.props.vexpand = True # Whether to expand vertically 25 | # https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Widget.html#Gtk.Widget.props.vexpand 26 | self.main_vertical_box.append(self.quit_button) 27 | 28 | def on_about_button_clicked(self,about_clicked_button,msg): 29 | print(msg) 30 | 31 | def on_quit_button_clicked(self,quit_clicked_button): 32 | self.app_.quit() 33 | 34 | class MyApp(Gtk.Application): 35 | def __init__(self, **kwargs): 36 | super().__init__(**kwargs) 37 | 38 | def do_activate(self): 39 | active_window = self.props.active_window 40 | if active_window: 41 | active_window.present() 42 | else: 43 | self.win = MainWindow(application=self) 44 | self.win.present() 45 | 46 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 47 | app.run(sys.argv) 48 | ``` 49 | 50 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/Box_LAYOUT/Screenshot.png "Screenshot") 51 | 52 | [Gtk.Box](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Box.html) 53 | -------------------------------------------------------------------------------- /Box_LAYOUT/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/Box_LAYOUT/Screenshot.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-gtk4-examples 2 | 3 | # Basic 4 | 5 | * [1-Gtk.Window](https://github.com/yucefsourani/python-gtk4-examples/tree/main/window) 6 | 7 | * [2-Gtk.ApplicationWindow](https://github.com/yucefsourani/python-gtk4-examples/tree/main/applicationwindow) 8 | 9 | * [3-Gtk.Button](https://github.com/yucefsourani/python-gtk4-examples/tree/main/button) 10 | 11 | * [4-Gtk.Box](https://github.com/yucefsourani/python-gtk4-examples/tree/main/Box_LAYOUT) 12 | 13 | * [5-Gtk.Label](https://github.com/yucefsourani/python-gtk4-examples/tree/main/label) 14 | 15 | * [6-Gtk.HeaderBar+Gtk.MenuButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/headerbar_and_menubutton) 16 | 17 | * [7-Gtk.Spinner](https://github.com/yucefsourani/python-gtk4-examples/tree/main/spinner) 18 | 19 | * [8-Gtk.ToggleButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/togglebutton) 20 | 21 | * [9-Gtk.ProgressBar](https://github.com/yucefsourani/python-gtk4-examples/tree/main/progressbar) 22 | 23 | * [10-Gtk.LinkButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/linkbutton) 24 | 25 | * [11-Gtk.Switch](https://github.com/yucefsourani/python-gtk4-examples/tree/main/switch) 26 | 27 | * [12-Gtk.VolumeButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/volumebutton) 28 | 29 | * [13-Gtk.CheckButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/checkbutton) 30 | 31 | * [14-Gtk.ColorButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/colorbutton) 32 | 33 | * [15-Gtk.ComboBoxText](https://github.com/yucefsourani/python-gtk4-examples/tree/main/comboboxtext) 34 | 35 | * [16-Gtk.Stack](https://github.com/yucefsourani/python-gtk4-examples/tree/main/stack) 36 | 37 | * [17-Gtk.FlowBox + Gtk.Stack + Gtk.Image + Gtk.CssProvider](https://github.com/yucefsourani/python-gtk4-examples/tree/main/stack_flowbox_css_provider) 38 | 39 | * [18-Gtk.Entry](https://github.com/yucefsourani/python-gtk4-examples/tree/main/entry) 40 | 41 | * [19-Gtk.PasswordEntry](https://github.com/yucefsourani/python-gtk4-examples/tree/main/passwordentry) 42 | 43 | * [20-Gtk.InfoBar](https://github.com/yucefsourani/python-gtk4-examples/tree/main/infobar) 44 | 45 | * [21-Gtk.AppChooserButton](https://github.com/yucefsourani/python-gtk4-examples/tree/main/appchooserbutton) 46 | 47 | * [22-Gtk.ListBox+Gtk.SearchBar](https://github.com/yucefsourani/python-gtk4-examples/tree/main/listbox_searchbar) 48 | 49 | * [23-Adw.ApplicationWindow+Gtk.Scale+Adw.Clamp+AdwExpanderRow](https://github.com/yucefsourani/python-gtk4-examples/tree/main/libadwaita_scale_clamp_expanderrow) 50 | 51 | * [24-Adw.ApplicationWindow+Gtk.Scale+Adw.Clamp+AdwExpanderRow+Gtk.SearchBar](https://github.com/yucefsourani/python-gtk4-examples/tree/main/libadwaita_scale_clamp_expanderrow_searchbar) 52 | 53 | * [25-Gtk.ListView (Simple Example)](https://github.com/yucefsourani/python-gtk4-examples/tree/main/simple_list_view_example) 54 | 55 | * [26-Gio.Settings (Bind Gnome Shell Setting To Switch Row) ](https://github.com/yucefsourani/python-gtk4-examples/tree/main/gio_settings) 56 | 57 | # Full small programs 58 | 59 | * [Pyscanbc Scan barcode by zbar gtreamer plugin](https://github.com/yucefsourani/python-gtk4-examples/tree/main/small_programs/pyscanbc) 60 | 61 | * [pyrandompics Get Random Pictures From unsplash.com](https://github.com/yucefsourani/python-gtk4-examples/tree/main/small_programs/pyrandompics) 62 | 63 | * [Simple Timer](https://github.com/yucefsourani/python-gtk4-examples/tree/main/small_programs/timer) 64 | -------------------------------------------------------------------------------- /appchooserbutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.AppChooserButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | self.set_default_size(400, 200) 14 | 15 | self.main_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 16 | self.set_child(self.main_box) 17 | 18 | app_chooser_button = Gtk.AppChooserButton.new("application/pdf") 19 | app_chooser_button.set_heading("PDF FILE") 20 | app_chooser_button.set_modal(True) 21 | app_chooser_button.set_show_default_item(True) # default program for application/pdf 22 | app_chooser_button.set_show_dialog_item(True) # enable Other application button 23 | app_chooser_button.append_separator() 24 | app_chooser_button.append_custom_item("CUSTOM","Custom",Gio.ThemedIcon.new("x-office-address-book-symbolic"))# name label icon 25 | app_chooser_button.connect("custom-item-activated",self.on_custom_item_activate) 26 | app_chooser_button.connect("changed",self.on_item_changed) 27 | self.main_box.append(app_chooser_button) 28 | 29 | print_selected_app_name_button = Gtk.Button.new() 30 | print_selected_app_name_button.props.label = "Print Selected App" 31 | print_selected_app_name_button.connect("clicked",self.on_print_selected_app_name_button_clicked,app_chooser_button) 32 | self.main_box.append(print_selected_app_name_button) 33 | 34 | launch_selected_app_button = Gtk.Button.new() 35 | launch_selected_app_button.props.label = "Launch Selected App" 36 | launch_selected_app_button.connect("clicked",self.on_launch_selected_app_button_clicked,app_chooser_button) 37 | self.main_box.append(launch_selected_app_button) 38 | 39 | def on_custom_item_activate(self,app_chooser_button,item_name): 40 | print(item_name) #CUSTOM 41 | 42 | def on_item_changed(self,app_chooser_button): 43 | #https://lazka.github.io/pgi-docs/Gio-2.0/classes/AppInfo.html#Gio.AppInfo 44 | appinfo = app_chooser_button.get_app_info() 45 | if appinfo: 46 | print(appinfo.get_executable()) 47 | print(appinfo.get_icon()) 48 | print(appinfo.get_id()) 49 | print(appinfo.get_name()) 50 | print(appinfo.get_supported_types()) 51 | print(appinfo.get_description()) 52 | print(appinfo.get_display_name()) 53 | 54 | def on_print_selected_app_name_button_clicked(self,print_selected_app_name_button,app_chooser_button): 55 | #https://lazka.github.io/pgi-docs/Gio-2.0/classes/AppInfo.html#Gio.AppInfo 56 | appinfo = app_chooser_button.get_app_info() 57 | if appinfo: 58 | print(appinfo.get_executable()) 59 | print(appinfo.get_icon()) 60 | print(appinfo.get_id()) 61 | print(appinfo.get_name()) 62 | print(appinfo.get_supported_types()) 63 | print(appinfo.get_description()) 64 | print(appinfo.get_display_name()) 65 | 66 | def on_launch_selected_app_button_clicked(self,launch_selected_app_button,app_chooser_button): 67 | #https://lazka.github.io/pgi-docs/Gio-2.0/classes/AppInfo.html#Gio.AppInfo 68 | appinfo = app_chooser_button.get_app_info() 69 | if appinfo: 70 | launch_selected_app_button.set_sensitive(False)#disable button 71 | appinfo.launch_uris_async(None,None,None,self.on_launch_finish,launch_selected_app_button) 72 | #https://amolenaar.github.io/pgi-docs/Gio-2.0/classes/AppInfo.html#Gio.AppInfo.launch_uris_async 73 | 74 | def on_launch_finish(self,appinfo, result,launch_selected_app_button): 75 | #https://lazka.github.io/pgi-docs/Gio-2.0/callbacks.html#Gio.AsyncReadyCallback 76 | #https://lazka.github.io/pgi-docs/Gio-2.0/classes/AppInfo.html#Gio.AppInfo.launch_uris_finish 77 | try: 78 | status = appinfo.launch_uris_finish(result) 79 | print(status) 80 | except Exception as e: 81 | print(e) 82 | launch_selected_app_button.set_sensitive(True)#enable button 83 | 84 | class MyApp(Gtk.Application): 85 | def __init__(self, **kwargs): 86 | super().__init__(**kwargs) 87 | 88 | def do_activate(self): 89 | active_window = self.props.active_window 90 | if active_window: 91 | active_window.present() 92 | else: 93 | self.win = MainWindow(application=self) 94 | self.win.present() 95 | 96 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 97 | app.run(sys.argv) 98 | ``` 99 | 100 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/appchooserbutton/Screenshot.png "Screenshot") 101 | 102 | [Gtk.AppChooserButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/AppChooserButton.html) 103 | -------------------------------------------------------------------------------- /appchooserbutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/appchooserbutton/Screenshot.png -------------------------------------------------------------------------------- /applicationwindow/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ApplicationWindow 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.set_default_size(800, 600) 13 | self.app_ = self.get_application() 14 | 15 | class MyApp(Gtk.Application): 16 | def __init__(self, **kwargs): 17 | super().__init__(**kwargs) 18 | 19 | def do_activate(self): 20 | active_window = self.props.active_window 21 | if active_window: 22 | active_window.present() 23 | else: 24 | self.win = MainWindow(application=self) 25 | self.win.present() 26 | 27 | 28 | 29 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 30 | app.run(sys.argv) 31 | ``` 32 | 33 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/applicationwindow/Screenshot_1.png "Screenshot") 34 | 35 | [Gtk.Application](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Application.html) 36 | 37 | [Gtk.ApplicationWindow](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/ApplicationWindow.html) 38 | -------------------------------------------------------------------------------- /applicationwindow/Screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/applicationwindow/Screenshot_1.png -------------------------------------------------------------------------------- /button/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Button 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.button = Gtk.Button.new_with_label("Quit") 15 | self.button.connect("clicked",self.on_quit_button_clicked) 16 | 17 | self.set_child(self.button) 18 | 19 | def on_quit_button_clicked(self,clicked_button): 20 | self.app_.quit() 21 | 22 | class MyApp(Gtk.Application): 23 | def __init__(self, **kwargs): 24 | super().__init__(**kwargs) 25 | 26 | def do_activate(self): 27 | active_window = self.props.active_window 28 | if active_window: 29 | active_window.present() 30 | else: 31 | self.win = MainWindow(application=self) 32 | self.win.present() 33 | 34 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 35 | app.run(sys.argv) 36 | ``` 37 | 38 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/button/Screenshot.png "Screenshot") 39 | 40 | [Gtk.Button](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Button.html) 41 | -------------------------------------------------------------------------------- /button/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/button/Screenshot.png -------------------------------------------------------------------------------- /checkbutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.CheckButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 15 | self.set_child(self.main_vertical_box) 16 | 17 | spinner1 = Gtk.Spinner.new() 18 | self.main_vertical_box.append(spinner1) 19 | 20 | self.start_stop_spinner1_button = Gtk.CheckButton.new_with_label("Start/Stop Spinner1") 21 | self.start_stop_spinner1_button.connect("toggled",self.on_start_stop_spinner_button_toggled,spinner1) 22 | self.main_vertical_box.append(self.start_stop_spinner1_button) 23 | 24 | 25 | self.main_vertical_box.append(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL)) 26 | 27 | spinner2 = Gtk.Spinner.new() 28 | self.main_vertical_box.append(spinner2) 29 | 30 | spinner2_hbox = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,1) 31 | self.main_vertical_box.append(spinner2_hbox) 32 | 33 | self.start_spinner2_button = Gtk.CheckButton.new_with_label("Start Spinner2") 34 | self.start_spinner2_button.connect("toggled",self.on_start_stop_spinner_button_toggled,spinner2) 35 | spinner2_hbox.append(self.start_spinner2_button) 36 | 37 | self.stop_spinner2_button = Gtk.CheckButton.new_with_label("Stop Spinner2") 38 | spinner2_hbox.append(self.stop_spinner2_button) 39 | 40 | self.start_spinner2_button.set_group(self.stop_spinner2_button) 41 | 42 | 43 | def on_start_stop_spinner_button_toggled(self,start_stop_spinner_button,spinner): 44 | if start_stop_spinner_button.get_active(): 45 | spinner.start() 46 | else: 47 | spinner.stop() 48 | 49 | class MyApp(Gtk.Application): 50 | def __init__(self, **kwargs): 51 | super().__init__(**kwargs) 52 | 53 | def do_activate(self): 54 | active_window = self.props.active_window 55 | if active_window: 56 | active_window.present() 57 | else: 58 | self.win = MainWindow(application=self) 59 | self.win.present() 60 | 61 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 62 | app.run(sys.argv) 63 | ``` 64 | 65 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/checkbutton/Screenshot.png "Screenshot") 66 | 67 | [Gtk.CheckButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/CheckButton.html) 68 | -------------------------------------------------------------------------------- /checkbutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/checkbutton/Screenshot.png -------------------------------------------------------------------------------- /colorbutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ColorButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio, Gdk 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 15 | self.set_child(self.main_vertical_box) 16 | 17 | 18 | self.color_button1 = Gtk.ColorButton.new() 19 | self.color_button1.set_use_alpha(True) 20 | self.color_button1.connect("color-set",self.on_color_set) 21 | self.main_vertical_box.append(self.color_button1) 22 | 23 | self.color_button2 = Gtk.ColorButton.new() 24 | self.color_button2.set_use_alpha(True) 25 | mycolor = Gdk.RGBA() 26 | mycolor.parse("rgba(255,255,255,0.30)") 27 | #https://lazka.github.io/pgi-docs/index.html#Gdk-4.0/classes/RGBA.html#Gdk.RGBA.parse 28 | self.color_button2.set_rgba(mycolor) 29 | 30 | colors_list = [] 31 | for i in range(10): 32 | custom_palette_color = Gdk.RGBA() 33 | custom_palette_color.parse("rgba({},{},{},1.0)".format(i*10,255-(i*20),300)) 34 | colors_list.append(custom_palette_color) 35 | self.color_button2.add_palette(Gtk.Orientation.HORIZONTAL,5,colors_list) 36 | self.color_button2.connect("color-set",self.on_color_set) 37 | self.main_vertical_box.append(self.color_button2) 38 | 39 | 40 | def on_color_set(self,color_button): 41 | color = color_button.get_rgba() # return Gdk.RGBA 42 | print(color.hash()) 43 | print(color.to_string()) 44 | print(color.alpha) # 0.0 to 1.0 45 | print(color.blue)# 0.0 to 1.0 46 | print(color.green)# 0.0 to 1.0 47 | print(color.red)# 0.0 to 1.0 48 | 49 | print("====================================") 50 | 51 | print(int(color.alpha*255)) 52 | print(int(color.blue*255)) 53 | print(int(color.green*255)) 54 | print(int(color.red*255)) 55 | 56 | 57 | class MyApp(Gtk.Application): 58 | def __init__(self, **kwargs): 59 | super().__init__(**kwargs) 60 | 61 | def do_activate(self): 62 | active_window = self.props.active_window 63 | if active_window: 64 | active_window.present() 65 | else: 66 | self.win = MainWindow(application=self) 67 | self.win.present() 68 | 69 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 70 | app.run(sys.argv) 71 | ``` 72 | 73 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/colorbutton/Screenshot.png "Screenshot") 74 | 75 | [Gtk.ColorButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/ColorButton.html) 76 | -------------------------------------------------------------------------------- /colorbutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/colorbutton/Screenshot.png -------------------------------------------------------------------------------- /comboboxtext/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ComboBoxText 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | 10 | class MainWindow(Gtk.ApplicationWindow): 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | self.app_ = self.get_application() 14 | 15 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 16 | self.set_child(self.main_vertical_box) 17 | 18 | data_to_show = ["Male","Female"] 19 | 20 | self.combobox_text1 = Gtk.ComboBoxText.new() 21 | self.main_vertical_box.append(self.combobox_text1) 22 | for i in data_to_show: 23 | self.combobox_text1.append_text(i) 24 | self.combobox_text1.set_active(0) # active first text in data_to_show 25 | 26 | print_button1 = Gtk.Button.new() 27 | print_button1.props.label = "Print actived text From ComboBoxText1 " 28 | print_button1.connect("clicked",self.on_print_button_clicked,self.combobox_text1) 29 | self.main_vertical_box.append(print_button1) 30 | 31 | self.combobox_text2 = Gtk.ComboBoxText.new_with_entry() 32 | for i in data_to_show: 33 | self.combobox_text2.append_text(i) 34 | self.combobox_text2.set_active(0) 35 | self.main_vertical_box.append(self.combobox_text2) 36 | 37 | print_button2 = Gtk.Button.new() 38 | print_button2.props.label = "Print actived text From ComboBoxText2 " 39 | print_button2.connect("clicked",self.on_print_button_clicked,self.combobox_text2) 40 | self.main_vertical_box.append(print_button2) 41 | 42 | def on_print_button_clicked(self,p_button,combobox_text): 43 | print(combobox_text.get_active_text()) 44 | 45 | class MyApp(Gtk.Application): 46 | def __init__(self, **kwargs): 47 | super().__init__(**kwargs) 48 | 49 | def do_activate(self): 50 | active_window = self.props.active_window 51 | if active_window: 52 | active_window.present() 53 | else: 54 | self.win = MainWindow(application=self) 55 | self.win.present() 56 | 57 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 58 | app.run(sys.argv) 59 | ``` 60 | 61 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/comboboxtext/Screenshot.png "Screenshot") 62 | 63 | [Gtk.ComboBoxText](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/ComboBoxText.html) 64 | -------------------------------------------------------------------------------- /comboboxtext/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/comboboxtext/Screenshot.png -------------------------------------------------------------------------------- /entry/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Entry 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | self.set_default_size(600, 400) 14 | 15 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 16 | self.set_child(self.main_vertical_box) 17 | 18 | model = Gtk.ListStore.new([str]) 19 | for i in ("Admin","admin","Administrator","administrator"): 20 | model.append([i]) 21 | completion = Gtk.EntryCompletion.new() 22 | completion.set_minimum_key_length(1) # the minimum length of the key in order to start completing 23 | completion.set_model(model) 24 | completion.set_text_column(0) # first item in [str] to show 25 | 26 | self.entry = Gtk.Entry.new() 27 | self.main_vertical_box.append(self.entry) 28 | self.entry.set_completion(completion) 29 | self.entry.set_has_frame(True) # True is default 30 | self.entry.props.margin_start = 20 31 | self.entry.props.margin_end = 20 32 | self.entry.props.margin_top = 20 33 | self.entry.props.margin_bottom = 20 34 | self.entry.set_placeholder_text("Enter Username...") 35 | self.entry.set_alignment(0) #start center end from 0 to 1 example : 0.1 0.2 0.3 ... 36 | self.entry.set_icon_from_icon_name( Gtk.EntryIconPosition.SECONDARY ,"edit-clear") 37 | self.entry.set_icon_tooltip_markup( Gtk.EntryIconPosition.SECONDARY ,"Clear Text") # markup bold 38 | self.entry.set_input_purpose( Gtk.InputPurpose.FREE_FORM ) # This information is useful for on-screen keyboards and similar input methods to decide which keys should be presented to the user. 39 | self.entry.set_max_length( 20 ) # max char 20 40 | self.entry.connect("icon_press",self.on_icon_pressed) 41 | 42 | self.entry_buffer = self.entry.get_buffer() 43 | self.entry_buffer.connect("notify::text",self.on_text_changed) 44 | 45 | def on_icon_pressed(self,entry,icon_pos): 46 | if icon_pos == Gtk.EntryIconPosition.SECONDARY: 47 | self.entry_buffer.set_text("",0) # clear 48 | 49 | def on_text_changed(self,buffer_,prop): 50 | print(buffer_.props.text) 51 | text_length = len(buffer_.props.text) 52 | self.entry.set_progress_fraction(text_length*0.05) # optional# max text length 20 look at line 36 - fraction from 0 to 1 53 | 54 | class MyApp(Gtk.Application): 55 | def __init__(self, **kwargs): 56 | super().__init__(**kwargs) 57 | 58 | def do_activate(self): 59 | active_window = self.props.active_window 60 | if active_window: 61 | active_window.present() 62 | else: 63 | self.win = MainWindow(application=self) 64 | self.win.present() 65 | 66 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 67 | app.run(sys.argv) 68 | ``` 69 | 70 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/entry/Screenshot.png "Screenshot") 71 | 72 | [Gtk.Entry](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Entry.html) 73 | -------------------------------------------------------------------------------- /entry/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/entry/Screenshot.png -------------------------------------------------------------------------------- /gio_settings/README.md: -------------------------------------------------------------------------------- 1 | # Gio.Settings Bind Gnome Shell setting To Switch row 2 | 3 | ```python 4 | 5 | import sys 6 | import gi 7 | gi.require_version("Gtk","4.0") 8 | gi.require_version("Adw","1") 9 | from gi.repository import Gtk,Gio,Adw 10 | 11 | class MainWindow(Adw.ApplicationWindow): 12 | def __init__(self, *args, **kwargs): 13 | super().__init__(*args, **kwargs) 14 | self.set_default_size(800, 600) 15 | self.app_ = self.get_application() 16 | 17 | self.mainvbox = Gtk.Box.new( Gtk.Orientation.VERTICAL,5) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 18 | 19 | self.set_content(self.mainvbox) # no set_child in Adw.ApplicationWindow 20 | 21 | headerbar = Adw.HeaderBar.new() 22 | self.mainvbox.append(headerbar) # no headerbar in Adw.ApplicationWindow 23 | 24 | clamp = Adw.Clamp.new() 25 | self.mainvbox.append(clamp) 26 | clamp.set_maximum_size(500) # max width of clamp and her child when maximize window is 500 27 | 28 | self.listbox = Gtk.ListBox.new() 29 | self.listbox.set_css_classes(["boxed-list"]) 30 | clamp.set_child(self.listbox) # max width is 500 31 | 32 | 33 | action_row = Adw.SwitchRow.new() 34 | self.listbox.append(action_row) 35 | if Adw.get_major_version() == 1 and Adw.get_minor_version() >2: 36 | action_row.set_title_lines(1) # number of line before wrap title text (require libAdwaita version > 1.2) 37 | action_row.set_subtitle_lines(4) # number of line before wrap subtitle text (require libAdwaita version > 1.2) 38 | 39 | action_row.add_prefix(Gtk.Image.new_from_icon_name("audio-volume-overamplified-symbolic")) # use https://flathub.org/apps/org.gnome.design.IconLibrary 40 | action_row.set_title("Gnome Volume Above") 41 | action_row.set_subtitle("Allow Volume Above 100 Percent") 42 | 43 | # gsettings list-recursively org.gnome.desktop.sound 44 | self.settings = Gio.Settings.new("org.gnome.desktop.sound") 45 | self.settings.bind("allow-volume-above-100-percent",action_row,"active", Gio.SettingsBindFlags.DEFAULT) 46 | # https://lazka.github.io/pgi-docs/#Gio-2.0/classes/Settings.html#Gio.Settings.bind 47 | 48 | 49 | class MyApp(Adw.Application): 50 | def __init__(self, **kwargs): 51 | super().__init__(**kwargs) 52 | 53 | def do_activate(self): 54 | active_window = self.props.active_window 55 | if active_window: 56 | active_window.present() 57 | else: 58 | self.win = MainWindow(application=self) 59 | self.win.present() 60 | 61 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 62 | app.run(sys.argv) 63 | ``` 64 | 65 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/gio_settings/Screenshot1.png "Screenshot") 66 | 67 | [Gio.Settings](https://lazka.github.io/pgi-docs/#Gio-2.0/classes/Settings.html#Gio.Settings) 68 | 69 | [Adw.SwitchRow](https://lazka.github.io/pgi-docs/#Adw-1/classes/SwitchRow.html#Adw.SwitchRow) 70 | -------------------------------------------------------------------------------- /gio_settings/Screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/gio_settings/Screenshot1.png -------------------------------------------------------------------------------- /headerbar_and_menubutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.HeaderBar + Gtk.MenuButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | MENU_XML=""" 10 | 11 | 12 | 13 |
14 | 15 | win.about 16 | _About 17 | 18 | 19 | win.quit 20 | _Quit 21 | <Primary>Q 22 | 23 |
24 |
25 |
26 | """ 27 | 28 | class MainWindow(Gtk.ApplicationWindow): 29 | def __init__(self, *args, **kwargs): 30 | super().__init__(*args, **kwargs) 31 | self.app_ = self.get_application() 32 | 33 | self.headerbar = Gtk.HeaderBar.new() 34 | self.set_titlebar(self.headerbar) 35 | self.headerbar.set_title_widget(Gtk.Label.new("MyProgram Title")) #can use any widget 36 | self.headerbar.set_show_title_buttons(True) # Show|Hide Close Minimize Maximize (True by default) 37 | 38 | quit_action = Gio.SimpleAction.new("quit", None) # look at MENU_XML win.quit 39 | quit_action.connect("activate", self.on_quit_action_actived) 40 | self.add_action(quit_action) # (self window) == win in MENU_XML 41 | 42 | about_action = Gio.SimpleAction.new("about", None) # look at MENU_XML win.about 43 | about_action.connect("activate", self.on_about_action_actived) 44 | self.add_action(about_action) # (self window) == win in MENU_XML 45 | 46 | self.menu_button = Gtk.MenuButton.new() 47 | self.headerbar.pack_end(self.menu_button) # or pack_start 48 | menu = Gtk.Builder.new_from_string(MENU_XML, -1).get_object("app-menu") 49 | self.menu_button.set_icon_name("open-menu-symbolic") # from Pre-installed standard linux icon names 50 | #https://specifications.freedesktop.org/icon-naming-spec/latest/ar01s04.html 51 | self.menu_button.set_menu_model(menu) 52 | 53 | def on_about_action_actived(self, action, param=None): 54 | print("About") 55 | 56 | def on_quit_action_actived(self, action, param=None): 57 | self.app_.quit() 58 | 59 | class MyApp(Gtk.Application): 60 | def __init__(self, **kwargs): 61 | super().__init__(**kwargs) 62 | 63 | def do_activate(self): 64 | active_window = self.props.active_window 65 | if active_window: 66 | active_window.present() 67 | else: 68 | self.win = MainWindow(application=self) 69 | self.win.present() 70 | 71 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 72 | app.run(sys.argv) 73 | ``` 74 | 75 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/headerbar_and_menubutton/Screenshot.png "Screenshot") 76 | 77 | 78 | 79 | [Gtk.HeaderBar](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/HeaderBar.html) 80 | 81 | 82 | 83 | [Gtk.MenuButton](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/MenuButton.html) 84 | -------------------------------------------------------------------------------- /headerbar_and_menubutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/headerbar_and_menubutton/Screenshot.png -------------------------------------------------------------------------------- /infobar/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.InfoBar 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | self.set_default_size(400, 200) 14 | 15 | self.main_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 16 | self.set_child(self.main_box) 17 | 18 | infobar = Gtk.InfoBar.new() 19 | infobar.set_revealed(False) # hide 20 | infobar.set_show_close_button(True) # When clicked it emits the response Gtk.ResponseType.CLOSE 21 | infobar.add_button("Yes", Gtk.ResponseType.YES ) # Action button on side. When clicked it emits the response Gtk.ResponseType.YES 22 | infobar.add_button("No", Gtk.ResponseType.NO ) # Action button on side. When clicked it emits the response Gtk.ResponseType.NO 23 | self.main_box.append(infobar) 24 | 25 | self.message_to_show_in_infobar = Gtk.Label.new() 26 | infobar.add_child(self.message_to_show_in_infobar) 27 | 28 | infobar.connect("response",self.on_infobar_action_button_clicked) 29 | 30 | install_geany_button = Gtk.Button.new() 31 | install_geany_button.add_css_class("suggested-action") # try add_css_class("destructive-action") 32 | install_geany_button.props.label = "Install Geany IDE" 33 | install_geany_button.connect("clicked",self.on_install_geany_button_clicked,infobar,"Yes|No Install Geany ?",["pkexe dnf install geany -y"]) 34 | self.main_box.append(install_geany_button) 35 | 36 | def on_install_geany_button_clicked(self,i_geany_button,infobar,message,commands_to_run): 37 | self.message_to_show_in_infobar.set_label(message) 38 | infobar.set_message_type(Gtk.MessageType.QUESTION ) 39 | infobar.set_revealed(True) 40 | infobar.commands_to_run = commands_to_run 41 | 42 | def on_infobar_action_button_clicked(self,infobar,response_id): 43 | if response_id == Gtk.ResponseType.CLOSE: 44 | print("Close Clicked") 45 | elif response_id == Gtk.ResponseType.YES: 46 | print("Yes Clicked") 47 | print("Running Commands {}".format(infobar.commands_to_run)) 48 | 49 | elif response_id == Gtk.ResponseType.NO: 50 | print("No Clicked") 51 | print("Running Commands {} Canceled".format(infobar.commands_to_run)) 52 | 53 | infobar.set_revealed(False) # hide 54 | 55 | class MyApp(Gtk.Application): 56 | def __init__(self, **kwargs): 57 | super().__init__(**kwargs) 58 | 59 | def do_activate(self): 60 | active_window = self.props.active_window 61 | if active_window: 62 | active_window.present() 63 | else: 64 | self.win = MainWindow(application=self) 65 | self.win.present() 66 | 67 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 68 | app.run(sys.argv) 69 | ``` 70 | 71 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/infobar/Screenshot.png "Screenshot") 72 | 73 | [Gtk.InfoBar](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/InfoBar.html) 74 | -------------------------------------------------------------------------------- /infobar/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/infobar/Screenshot.png -------------------------------------------------------------------------------- /label/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Label 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio,Pango 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | 13 | self.set_default_size(100,100) 14 | self.app_ = self.get_application() 15 | 16 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,5) 17 | self.set_child(self.main_vertical_box) 18 | 19 | self.text_label1 = Gtk.Label.new("Gtk.Label Example 111 111 111 1111 111 111 111 111 111 111 111 11") 20 | self.text_label1.props.wrap = True 21 | self.text_label1.set_wrap_mode(Pango.WrapMode.WORD) 22 | # https://lazka.github.io/pgi-docs/Pango-1.0/enums.html#Pango.WrapMode 23 | self.main_vertical_box.append(self.text_label1) 24 | 25 | 26 | self.wrap_or_ellipsize_button = Gtk.Button.new() 27 | self.wrap_or_ellipsize_button.set_label("Ellipsize Text") 28 | self.wrap_or_ellipsize_button.connect("clicked",self.on_wrap_or_ellipsize_button_clicked) 29 | self.main_vertical_box.append(self.wrap_or_ellipsize_button) 30 | 31 | def on_wrap_or_ellipsize_button_clicked(self,wrap_or_ellipsize_clicked_button): 32 | if self.text_label1.props.wrap: # if True 33 | self.text_label1.props.wrap = False 34 | self.text_label1.set_ellipsize( Pango.EllipsizeMode.END) 35 | # https://lazka.github.io/pgi-docs/Pango-1.0/enums.html#Pango.EllipsizeMode 36 | wrap_or_ellipsize_clicked_button.set_label("Wrap Text") 37 | else: 38 | self.text_label1.set_ellipsize( Pango.EllipsizeMode.NONE) 39 | self.text_label1.props.wrap = True 40 | wrap_or_ellipsize_clicked_button.set_label("Ellipsize Text") 41 | 42 | class MyApp(Gtk.Application): 43 | def __init__(self, **kwargs): 44 | super().__init__(**kwargs) 45 | 46 | def do_activate(self): 47 | active_window = self.props.active_window 48 | if active_window: 49 | active_window.present() 50 | else: 51 | self.win = MainWindow(application=self) 52 | self.win.present() 53 | 54 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 55 | app.run(sys.argv) 56 | 57 | ``` 58 | 59 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/label/Screenshot.png "Screenshot") 60 | 61 | [Gtk.label](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Label.html) 62 | -------------------------------------------------------------------------------- /label/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/label/Screenshot.png -------------------------------------------------------------------------------- /libadwaita_scale_clamp_expanderrow/README.md: -------------------------------------------------------------------------------- 1 | # Adw.ApplicationWindow 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version("Gtk","4.0") 7 | gi.require_version("Adw","1") 8 | from gi.repository import Gtk,Gio,Adw 9 | 10 | class MainWindow(Adw.ApplicationWindow): 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | self.set_default_size(800, 600) 14 | self.app_ = self.get_application() 15 | 16 | self.mainvbox = Gtk.Box.new( Gtk.Orientation.VERTICAL,5) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 17 | 18 | self.set_content(self.mainvbox) # no set_child in Adw.ApplicationWindow 19 | 20 | headerbar = Adw.HeaderBar.new() 21 | self.mainvbox.append(headerbar) # no headerbar in Adw.ApplicationWindow 22 | 23 | clamp = Adw.Clamp.new() 24 | self.mainvbox.append(clamp) 25 | clamp.set_maximum_size(500) # max width of clamp and her child when maximize window is 500 26 | 27 | self.listbox = Gtk.ListBox.new() 28 | self.listbox.set_css_classes(["boxed-list"]) 29 | clamp.set_child(self.listbox) # max width is 500 30 | 31 | self.create_expander_row() 32 | 33 | def create_expander_row(self): 34 | action_row = Adw.ExpanderRow.new() 35 | self.listbox.append(action_row) 36 | if Adw.get_major_version() == 1 and Adw.get_minor_version() >2: 37 | action_row.set_title_lines(1) # number of line before wrap title text (require libAdwaita version > 1.2) 38 | action_row.set_subtitle_lines(4) # number of line before wrap subtitle text (require libAdwaita version > 1.2) 39 | 40 | action_row.add_prefix(Gtk.Image.new_from_icon_name("audio-input-microphone-symbolic")) # use https://flathub.org/apps/org.gnome.design.IconLibrary 41 | action_row.set_title("My Title") 42 | action_row.set_subtitle("My Subtitle") 43 | 44 | scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL,0,10,2) 45 | scale.set_draw_value(True) 46 | scale.set_value(8) 47 | scale.add_mark(5,Gtk.PositionType.BOTTOM,"50%") 48 | action_row.add_row(scale) 49 | 50 | reset_button = Gtk.Button.new_with_label("Reset") 51 | reset_button.connect("clicked",self.on_reset_button_clicked,scale) 52 | reset_button.set_css_classes(["suggested-action","pill"]) 53 | action_row.add_action(reset_button) 54 | 55 | def on_reset_button_clicked(self,button,scale): 56 | scale.set_value(5) 57 | 58 | class MyApp(Adw.Application): 59 | def __init__(self, **kwargs): 60 | super().__init__(**kwargs) 61 | 62 | def do_activate(self): 63 | active_window = self.props.active_window 64 | if active_window: 65 | active_window.present() 66 | else: 67 | self.win = MainWindow(application=self) 68 | self.win.present() 69 | 70 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 71 | app.run(sys.argv) 72 | ``` 73 | 74 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/libadwaita_scale_clamp_expanderrow/Screenshot_1.png "Screenshot") 75 | 76 | 77 | 78 | [Adw.ApplicationWindow](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/ApplicationWindow.html) 79 | 80 | 81 | [Adw.Clamp](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/Clamp.html) 82 | 83 | 84 | [Adw.ExpanderRow](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/ExpanderRow.html) 85 | 86 | 87 | [Gtk.Scale](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Scale.html) 88 | 89 | -------------------------------------------------------------------------------- /libadwaita_scale_clamp_expanderrow/Screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/libadwaita_scale_clamp_expanderrow/Screenshot_1.png -------------------------------------------------------------------------------- /libadwaita_scale_clamp_expanderrow_searchbar/README.md: -------------------------------------------------------------------------------- 1 | # Adw.ApplicationWindow 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version("Gtk","4.0") 7 | gi.require_version("Adw","1") 8 | from gi.repository import Gtk,Gio,Adw 9 | 10 | class MainWindow(Adw.ApplicationWindow): 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | self.set_default_size(800, 600) 14 | self.app_ = self.get_application() 15 | 16 | self.mainvbox = Gtk.Box.new( Gtk.Orientation.VERTICAL,5) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 17 | self.set_content(self.mainvbox) # no set_child in Adw.ApplicationWindow 18 | 19 | self.headerbar = Adw.HeaderBar.new() 20 | self.mainvbox.append(self.headerbar) # no headerbar in Adw.ApplicationWindow 21 | 22 | clamp = Adw.Clamp.new() 23 | self.mainvbox.append(clamp) 24 | clamp.set_maximum_size(500) # max width of clamp and her child when maximize window is 500 25 | 26 | sw = Gtk.ScrolledWindow.new() # To scroll rows in Gtk.listbox 27 | clamp.set_child(sw) # max width is 500 28 | self.listbox = Gtk.ListBox.new() 29 | sw.set_child(self.listbox) 30 | self.listbox.props.vexpand = True 31 | self.listbox.set_css_classes(["boxed-list"]) 32 | 33 | self.create_searchbar() 34 | self.create_expander_row() 35 | 36 | def create_searchbar(self): 37 | search_entry = Gtk.SearchEntry.new() 38 | search_entry.connect("search_changed",self.on_input_text_to_search,self.listbox) # listbox to listbox.invalidate_filter() and start filter 39 | self.listbox.set_filter_func(self.run_filter_row,search_entry) # run_filter_row() to filder row (search_entry to get text to search) 40 | 41 | searchbar = Gtk.SearchBar.new() 42 | self.mainvbox.insert_child_after(searchbar,self.headerbar) # insert searchbar after headerbar 43 | searchbar.connect_entry(search_entry) 44 | searchbar.set_child(search_entry) # add search entry to searchbar 45 | searchbar.set_show_close_button(True) # show close button to close searcbar and stop filter 46 | searchbar.set_key_capture_widget(self) # capture keyboard input on main window focus 47 | 48 | def on_input_text_to_search(self,search_entry,listbox): 49 | listbox.invalidate_filter() # call function self.run_filter_row() ++> look at self.listbox.set_filter_func(self.run_filter_row) 50 | 51 | def run_filter_row(self,expander_row,search_entry): 52 | # run_filter_row get all expander rows in listbox (row by row) 53 | text_to_search = search_entry.get_text().strip().lower() 54 | if len(text_to_search) == 0: 55 | return True# if retun True show expander_row # if text length == 0 return True(show expander_row) 56 | if text_to_search in expander_row.get_title().lower() or text_to_search in expander_row.get_subtitle().lower(): 57 | return True # if retun True show expander_row 58 | 59 | def create_expander_row(self): 60 | for info_ in (("Microphone","Audio Input"),("Audio","Audio Output")): 61 | title = info_[0] 62 | subtitle = info_[1] 63 | action_row = Adw.ExpanderRow.new() 64 | self.listbox.append(action_row) 65 | if Adw.get_major_version() == 1 and Adw.get_minor_version() >2: 66 | action_row.set_title_lines(1) # number of line before wrap title text (require libAdwaita version > 1.2) 67 | action_row.set_subtitle_lines(4) # number of line before wrap subtitle text (require libAdwaita version > 1.2) 68 | 69 | action_row.add_prefix(Gtk.Image.new_from_icon_name("audio-input-microphone-symbolic")) # use https://flathub.org/apps/org.gnome.design.IconLibrary 70 | action_row.set_title(title) 71 | action_row.set_subtitle(subtitle) 72 | 73 | scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL,0,10,2) 74 | scale.set_draw_value(True) 75 | scale.set_value(8) 76 | scale.add_mark(5,Gtk.PositionType.BOTTOM,"50%") 77 | action_row.add_row(scale) 78 | 79 | reset_button = Gtk.Button.new_with_label("Reset") 80 | reset_button.connect("clicked",self.on_reset_button_clicked,scale) 81 | reset_button.set_css_classes(["suggested-action","pill"]) 82 | action_row.add_action(reset_button) 83 | 84 | def on_reset_button_clicked(self,button,scale): 85 | scale.set_value(5) 86 | 87 | class MyApp(Adw.Application): 88 | def __init__(self, **kwargs): 89 | super().__init__(**kwargs) 90 | 91 | def do_activate(self): 92 | active_window = self.props.active_window 93 | if active_window: 94 | active_window.present() 95 | else: 96 | self.win = MainWindow(application=self) 97 | self.win.present() 98 | 99 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 100 | app.run(sys.argv) 101 | ``` 102 | 103 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/libadwaita_scale_clamp_expanderrow_searchbar/Screenshot_1.png "Screenshot") 104 | 105 | 106 | 107 | [Adw.ApplicationWindow](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/ApplicationWindow.html) 108 | 109 | 110 | [Adw.Clamp](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/Clamp.html) 111 | 112 | 113 | [Adw.ExpanderRow](https://lazka.github.io/pgi-docs/index.html#Adw-1/classes/ExpanderRow.html) 114 | 115 | 116 | [Gtk.Scale](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Scale.html) 117 | 118 | 119 | [Gtk.SearchBar](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/SearchBar.html) 120 | 121 | 122 | [Gtk.SearchEntry](https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/SearchEntry.html) 123 | 124 | -------------------------------------------------------------------------------- /libadwaita_scale_clamp_expanderrow_searchbar/Screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/libadwaita_scale_clamp_expanderrow_searchbar/Screenshot_1.png -------------------------------------------------------------------------------- /linkbutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.LinkButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) 15 | self.set_child(self.main_vertical_box) 16 | 17 | self.linkbutton_1 = Gtk.LinkButton.new_with_label("https://arfedora.blogspot.com","MyWeb") 18 | self.main_vertical_box.append(self.linkbutton_1 ) 19 | 20 | h_separator = Gtk.Separator.new(Gtk.Orientation.HORIZONTAL) 21 | self.main_vertical_box.append(h_separator ) 22 | 23 | self.linkbutton_2 = Gtk.LinkButton.new("https://arfedora.blogspot.com") 24 | self.linkbutton_2.connect("activate-link",self.on_linkbutton_2_clicked) 25 | self.main_vertical_box.append(self.linkbutton_2 ) 26 | 27 | self.enable_disable_linkbutton2_open_link = Gtk.ToggleButton.new_with_label("Enable/Disable Open Second Link") 28 | self.main_vertical_box.append(self.enable_disable_linkbutton2_open_link ) 29 | 30 | def on_linkbutton_2_clicked(self,linkbutton_2 ): 31 | # To override the default behavior, you can connect to the ::activate-link signal and stop the propagation of the signal by returning True from your handler. 32 | is_active = self.enable_disable_linkbutton2_open_link.get_active() 33 | return is_active # if False open link if True ignore open link 34 | 35 | 36 | class MyApp(Gtk.Application): 37 | def __init__(self, **kwargs): 38 | super().__init__(**kwargs) 39 | 40 | def do_activate(self): 41 | active_window = self.props.active_window 42 | if active_window: 43 | active_window.present() 44 | else: 45 | self.win = MainWindow(application=self) 46 | self.win.present() 47 | 48 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 49 | app.run(sys.argv) 50 | ``` 51 | 52 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/linkbutton/Screenshot.png "Screenshot") 53 | 54 | [Gtk.LinkButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/LinkButton.html) 55 | -------------------------------------------------------------------------------- /linkbutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/linkbutton/Screenshot.png -------------------------------------------------------------------------------- /listbox_searchbar/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ListBox 2 | # Gtk.SearchBar 3 | 4 | ```python 5 | import sys 6 | import gi 7 | gi.require_version('Gtk', '4.0') 8 | from gi.repository import Gtk,Gio 9 | 10 | 11 | class MainWindow(Gtk.ApplicationWindow): 12 | def __init__(self, *args, **kwargs): 13 | super().__init__(*args, **kwargs) 14 | 15 | self.app_ = self.get_application() 16 | self.set_default_size(800, 600) 17 | 18 | show_searchbar_action = Gio.SimpleAction.new("show_searchbar") 19 | show_searchbar_action.connect("activate",self.on_show_searchbar_action_actived) 20 | 21 | self.app_.add_action(show_searchbar_action) 22 | self.app_.set_accels_for_action("app.show_searchbar",["F"]) 23 | 24 | self.main_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) 25 | self.set_child(self.main_box) 26 | 27 | self.searchentry = Gtk.SearchEntry.new() 28 | self.searchentry.connect("search_changed",self.on_search_entry_changed) 29 | 30 | self.searchbar = Gtk.SearchBar.new() 31 | self.searchbar.props.hexpand = True 32 | self.searchbar.props.vexpand = False 33 | self.searchbar.connect_entry(self.searchentry) 34 | self.searchbar.set_child(self.searchentry) 35 | self.searchbar.set_key_capture_widget(self) 36 | self.main_box.append(self.searchbar) 37 | 38 | self.listbox = Gtk.ListBox.new() 39 | self.listbox.props.hexpand = True 40 | self.listbox.props.vexpand = True 41 | self.listbox.set_selection_mode(Gtk.SelectionMode.NONE) 42 | self.listbox.set_show_separators(True) 43 | self.main_box.append(self.listbox) 44 | 45 | 46 | for i in ("Beirut","Saida","Lebanon","Palestine","Tripoli","Syria","Jordan","Iraq","Ksa","kuwait","Egypt","Oman"): 47 | row_hbox = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,0) 48 | row_hbox.MYTEXT = i # to filter later 49 | self.listbox.append(row_hbox) 50 | 51 | label = Gtk.Label.new(i) 52 | label.props.margin_start = 5 53 | label.props.hexpand = True 54 | label.set_halign(Gtk.Align.START) 55 | label.set_selectable(True) 56 | row_hbox.append(label) 57 | 58 | image = Gtk.Image.new_from_icon_name("contact-new-symbolic") 59 | image.props.margin_end = 5 60 | image.set_halign(Gtk.Align.END) 61 | row_hbox.append(image) 62 | 63 | self.listbox.set_filter_func(self.on_filter_invalidate) 64 | 65 | def on_show_searchbar_action_actived(self,action,parameter): 66 | self.searchbar.set_search_mode(True) # Ctrl+F To Active show_searchbar and show searchbar 67 | 68 | def on_search_entry_changed(self,searchentry): 69 | """The filter_func will be called for each row after the call, 70 | and it will continue to be called each time a row changes (via [method`Gtk`.ListBoxRow.changed]) 71 | or when [method`Gtk`.ListBox.invalidate_filter] is called. """ 72 | self.listbox.invalidate_filter() # run filter (run self.on_filter_invalidate look at self.listbox.set_filter_func(self.on_filter_invalidate) ) 73 | 74 | def on_filter_invalidate(self,row): 75 | text_to_search = self.searchentry.get_text().strip() # get text from searchentry and remove space from start and end 76 | if text_to_search.lower() in row.get_child().MYTEXT.lower(): # == row_hbox.MYTEXT (Gtk.ListBoxRow===>get_child()===>row_hbox.MYTEXT) 77 | return True # if True Show row 78 | return False 79 | 80 | class MyApp(Gtk.Application): 81 | def __init__(self, **kwargs): 82 | super().__init__(**kwargs) 83 | 84 | def do_activate(self): 85 | active_window = self.props.active_window 86 | if active_window: 87 | active_window.present() 88 | else: 89 | self.win = MainWindow(application=self) 90 | self.win.present() 91 | 92 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 93 | app.run(sys.argv) 94 | ``` 95 | 96 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/listbox_searchbar/Screenshot.png "Screenshot") 97 | 98 | [Gtk.ListBox](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/ListBox.html) 99 | 100 | [Gtk.SearchBar](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/SearchBar.html) 101 | -------------------------------------------------------------------------------- /listbox_searchbar/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/listbox_searchbar/Screenshot.png -------------------------------------------------------------------------------- /passwordentry/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.PasswordEntry 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | self.set_default_size(600, 400) 14 | 15 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 16 | self.set_child(self.main_vertical_box) 17 | 18 | self.password_entry = Gtk.PasswordEntry.new() 19 | self.password_entry.connect("notify::text",self.on_text_changed) 20 | self.password_entry.set_show_peek_icon(True) 21 | self.password_entry.props.placeholder_text = "Enter Password" 22 | self.password_entry.props.margin_start = 20 23 | self.password_entry.props.margin_end = 20 24 | self.password_entry.props.margin_top = 20 25 | self.password_entry.props.margin_bottom = 20 26 | self.main_vertical_box.append(self.password_entry) 27 | 28 | def on_text_changed(self,password_entry,prop): 29 | print(password_entry.props.text) 30 | # Gtk.PasswordEntry Implement Gtk.Editable 31 | https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Editable.html#properties 32 | 33 | 34 | class MyApp(Gtk.Application): 35 | def __init__(self, **kwargs): 36 | super().__init__(**kwargs) 37 | 38 | def do_activate(self): 39 | active_window = self.props.active_window 40 | if active_window: 41 | active_window.present() 42 | else: 43 | self.win = MainWindow(application=self) 44 | self.win.present() 45 | 46 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 47 | app.run(sys.argv) 48 | ``` 49 | 50 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/passwordentry/Screenshot.png "Screenshot") 51 | 52 | [Gtk.PasswordEntry](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/classes/PasswordEntry.html) 53 | -------------------------------------------------------------------------------- /passwordentry/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/passwordentry/Screenshot.png -------------------------------------------------------------------------------- /progressbar/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ProgressBar 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio,GLib,Pango 8 | import threading 9 | import time 10 | 11 | class MainWindow(Gtk.ApplicationWindow): 12 | def __init__(self, *args, **kwargs): 13 | super().__init__(*args, **kwargs) 14 | self.app_ = self.get_application() 15 | 16 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 17 | self.set_child(self.main_vertical_box) 18 | 19 | 20 | self.progressbar1 = Gtk.ProgressBar.new() 21 | self.progressbar1.set_show_text(True) 22 | self.progressbar1.set_ellipsize(Pango.EllipsizeMode.END) 23 | # https://lazka.github.io/pgi-docs/Pango-1.0/enums.html#Pango.EllipsizeMode 24 | self.main_vertical_box.append(self.progressbar1) 25 | 26 | first_progressbar_button = Gtk.Button.new() 27 | first_progressbar_button.props.label = "Run First ProgressBar" 28 | first_progressbar_button.connect("clicked",self.on_first_progressbar_button_clicked) 29 | self.main_vertical_box.append(first_progressbar_button) 30 | 31 | self.progressbar2 = Gtk.ProgressBar.new() 32 | self.progressbar2.set_pulse_step(0.5) 33 | self.progressbar2.set_inverted(True) 34 | self.main_vertical_box.append(self.progressbar2) 35 | 36 | second_progressbar_button = Gtk.Button.new() 37 | second_progressbar_button.props.label = "Run Second ProgressBar" 38 | second_progressbar_button.connect("clicked",self.on_second_progressbar_button_clicked) 39 | self.main_vertical_box.append(second_progressbar_button) 40 | 41 | 42 | def on_first_progressbar_button_clicked(self,first_progressbar_button): 43 | threading.Thread(target=self.__thread_first_progressbar_button_clicked,args=(first_progressbar_button,)).start() 44 | 45 | def __thread_first_progressbar_button_clicked(self,first_progressbar_button): 46 | # use GLib.idle_add to run gtk method from another thread 47 | GLib.idle_add(first_progressbar_button.set_sensitive,False) # Disable Start Task Button 48 | for i in range(5):# timeout for 5 second 49 | fraction = self.progressbar1.get_fraction() # float between 0.0 and 1.0 (The fraction should be between 0.0 and 1.0) 50 | fraction += 1/5 # 1/5 = 0.2 ===> pulse 0.2 every step (0.2 0.4 0.6 0.8 1) 51 | GLib.idle_add(self.progressbar1.set_fraction,fraction) # The fraction should be between 0.0 and 1.0, inclusive 52 | GLib.idle_add(self.progressbar1.set_text,"Task Is Runnnig %{}".format(int(fraction*100))) 53 | time.sleep(1) 54 | 55 | GLib.idle_add(self.progressbar1.set_text,"Task Is Done %100 ...") 56 | GLib.idle_add(self.progressbar1.set_fraction,0.0) # reset 57 | GLib.idle_add(first_progressbar_button.set_sensitive,True) # Enable Start Task Button 58 | 59 | def on_second_progressbar_button_clicked(self,second_progressbar_button): 60 | threading.Thread(target=self.__thread_second_progressbar_button_clicked,args=(second_progressbar_button,)).start() 61 | 62 | def __thread_second_progressbar_button_clicked(self,second_progressbar_button): 63 | for i in range(20):# timeout 64 | GLib.idle_add(self.progressbar2.pulse) 65 | time.sleep(0.2) 66 | GLib.idle_add(self.progressbar2.set_fraction,0.0) 67 | 68 | 69 | class MyApp(Gtk.Application): 70 | def __init__(self, **kwargs): 71 | super().__init__(**kwargs) 72 | 73 | def do_activate(self): 74 | active_window = self.props.active_window 75 | if active_window: 76 | active_window.present() 77 | else: 78 | self.win = MainWindow(application=self) 79 | self.win.present() 80 | 81 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 82 | app.run(sys.argv) 83 | ``` 84 | 85 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/progressbar/Screenshot.png "Screenshot") 86 | 87 | [Gtk.ProgressBar](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/ProgressBar.html) 88 | -------------------------------------------------------------------------------- /progressbar/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/progressbar/Screenshot.png -------------------------------------------------------------------------------- /simple_list_view_example/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ListView 2 | 3 | ```python 4 | 5 | import sys 6 | import gi 7 | gi.require_version('Gtk', '4.0') 8 | from gi.repository import Gtk,Gio,GObject,Gdk,GLib 9 | 10 | class MainWindow(Gtk.ApplicationWindow): 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | self.set_default_size(800, 600) 14 | 15 | sw = Gtk.ScrolledWindow.new() 16 | self.set_child(sw) 17 | 18 | headerbar = Gtk.HeaderBar.new() 19 | headerbar.set_title_widget(Gtk.Label.new("Simple ListView Example")) 20 | self.set_titlebar(headerbar) 21 | 22 | append_button = Gtk.Button.new_from_icon_name("list-add-symbolic") 23 | append_button.connect("clicked",self.on_add_button_clicked) 24 | headerbar.pack_start(append_button) 25 | 26 | # GtkStringList is a list model that wraps an array of strings. 27 | # The objects in the model are of type [class`Gtk`.StringObject 28 | # and have a “string” property that can be used inside expressions. 29 | self.stringlist = Gtk.StringList.new(None) 30 | 31 | # allows marking each item in a model as either selected or not selected 32 | # by wrapping a model with one of the GTK models provided for this purposes, 33 | # such as GtkNoSelection or GtkSingleSelection. 34 | self.single_selection_list_store = Gtk.SingleSelection.new(self.stringlist) 35 | 36 | # A GtkListItemFactory creates widgets for the items taken from a GListModel. 37 | # The GtkListItemFactory is tasked with creating widgets for items taken from the model when the views need 38 | # them and updating them as the items displayed by the view change. 39 | self.signal_factory = Gtk.SignalListItemFactory.new() 40 | 41 | 42 | # setup signal Emitted when a new listitem has been created and needs to be setup for use. 43 | self.signal_factory.connect("setup",self.on_setup) 44 | 45 | # bind signal emitted when [property`Gtk`.ListItem:item] has been set on a listitem and should be bound for use. 46 | self.signal_factory.connect("bind",self.on_object_bound_to_use) 47 | 48 | 49 | # https://docs.gtk.org/gtk4/section-list-widget.html 50 | self.listview = Gtk.ListView.new(self.single_selection_list_store,self.signal_factory) 51 | sw.set_child(self.listview) 52 | 53 | 54 | for i in range(100): 55 | self.stringlist.append(str(i)) 56 | 57 | # when 'selected' property changed 58 | self.single_selection_list_store.connect("notify::selected",self.on_item_list_selected) 59 | 60 | def on_setup(self,signal_factory, list_item): 61 | print("Setup--> Prepering Widgets Start") 62 | # GtkListItem is used by list widgets to represent items in a [iface`Gio`.ListModel] 63 | # GtkListItem objects are managed by the list widget (with its factory) and cannot be created by applications, 64 | # but they need to be populated by application code. This is done by calling [method`Gtk`.ListItem.set_child]. 65 | print(list_item) 66 | print(list_item.props.item) # item == None 67 | 68 | label = Gtk.Label.new() 69 | label.set_halign(Gtk.Align.START) 70 | list_item.set_child(label) 71 | print("Setup--> Prepering Widgets End\n") 72 | 73 | def on_object_bound_to_use(self,signal_factory, list_item): 74 | print("Bind--> modified Widgets Start") 75 | item = list_item.props.item # item == Gtk.StringObject (Gtk.StringObject wrapping str in Gtk.StringList) 76 | label = list_item.get_child()# label 77 | label.props.label = item.props.string #https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/StringObject.html#Gtk.StringObject.props.string 78 | print("Bind--> modified Widgets End\n") 79 | 80 | 81 | def on_item_list_selected(self,single_selection_list_store,props): 82 | selected_item = single_selection_list_store.props.selected_item # Gtk.StringObject 83 | string_value = selected_item.props.string 84 | position = single_selection_list_store.get_selected() 85 | print(f"Selected String = {string_value}") 86 | print(f"Selected Position = {position}") 87 | 88 | 89 | def on_add_button_clicked(self,button): 90 | self.stringlist.append("New") 91 | context = GLib.MainContext().default() 92 | while context.pending(): 93 | context.iteration(True) 94 | self.listview.scroll_to(self.stringlist.get_n_items()-1,Gtk.ListScrollFlags.FOCUS | Gtk.ListScrollFlags.SELECT ,None) 95 | 96 | class MyApp(Gtk.Application): 97 | def __init__(self, **kwargs): 98 | super().__init__(**kwargs) 99 | 100 | def do_activate(self): 101 | active_window = self.props.active_window 102 | if active_window: 103 | active_window.present() 104 | else: 105 | self.win = MainWindow(application=self) 106 | self.win.present() 107 | 108 | 109 | 110 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 111 | app.run(sys.argv) 112 | ``` 113 | 114 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/simple_list_view_example/Screenshot.png "Screenshot") 115 | 116 | [Gtk.ListView](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/ListView.html) 117 | 118 | [Gtk.StringList](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/StringList.html) 119 | -------------------------------------------------------------------------------- /simple_list_view_example/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/simple_list_view_example/Screenshot.png -------------------------------------------------------------------------------- /small_programs/pyrandompics/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /small_programs/pyrandompics/README.md: -------------------------------------------------------------------------------- 1 | # pyrandompics 2 | 3 | Get Random Pictures From https://unsplash.com . 4 | 5 | # Requires (available in fedora 39 official repos) 6 | 7 | ``` python3-dbus ``` 8 | 9 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyrandompics/Screenshot.png "Screenshot") 10 | 11 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyrandompics/Screenshot1.png "Screenshot") 12 | 13 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyrandompics/Screenshot2.png "Screenshot") 14 | 15 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyrandompics/Screenshot3.png "Screenshot") 16 | -------------------------------------------------------------------------------- /small_programs/pyrandompics/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyrandompics/Screenshot.png -------------------------------------------------------------------------------- /small_programs/pyrandompics/Screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyrandompics/Screenshot1.png -------------------------------------------------------------------------------- /small_programs/pyrandompics/Screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyrandompics/Screenshot2.png -------------------------------------------------------------------------------- /small_programs/pyrandompics/Screenshot3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyrandompics/Screenshot3.png -------------------------------------------------------------------------------- /small_programs/pyrandompics/pyrandompics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # 4 | # Copyright 2023 yucef sourani 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software 18 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 | # MA 02110-1301, USA. 20 | # 21 | # 22 | import sys 23 | import gi 24 | gi.require_version('Gtk', '4.0') 25 | gi.require_version('Soup', '3.0') 26 | gi.require_version('Adw', '1') 27 | from gi.repository import Gtk,Gio,GdkPixbuf,GLib,Gdk,Soup,Adw 28 | import dbus 29 | import os 30 | 31 | DOWNLOAD_LOCATION = os.path.join(GLib.get_user_special_dir( GLib.UserDirectory.DIRECTORY_PICTURES),"Randomwallpapers") 32 | GLib.mkdir_with_parents(DOWNLOAD_LOCATION,0o777) 33 | 34 | 35 | class CProxy(): 36 | def __init__(self,name,object_path,interface_name): 37 | self.__name = name 38 | self.__object_path = object_path 39 | self.__interface_name = interface_name 40 | self.bus = dbus.SessionBus() 41 | self.__main_object = self.bus.get_object(self.__name,self.__object_path) 42 | 43 | def get_method(self,method_name,interface = None): 44 | if not interface: 45 | interface = self.__interface_name 46 | return self.__main_object.get_dbus_method(method_name,interface) 47 | 48 | 49 | class MainWindow(Adw.ApplicationWindow): 50 | def __init__(self, *args, **kwargs): 51 | super().__init__(*args, **kwargs) 52 | #self.set_default_size(800, 600) 53 | self.proxy = CProxy("org.freedesktop.portal.Desktop", 54 | "/org/freedesktop/portal/desktop", 55 | "org.freedesktop.portal.Wallpaper") 56 | 57 | self.current_pixbuf = None 58 | 59 | self.mainvbox = Gtk.Box.new(orientation = Gtk.Orientation.VERTICAL,spacing = 5) 60 | self.set_content(self.mainvbox) 61 | 62 | headerbar = Gtk.HeaderBar.new() 63 | headerbar.set_title_widget(Gtk.Label.new("Pyrandompics")) 64 | self.mainvbox.append(headerbar) 65 | 66 | self.size_label = Gtk.Label.new() 67 | self.size_label.add_css_class("success") 68 | self.size_label.add_css_class("title-4") 69 | self.size_label.add_css_class("dim-label") 70 | headerbar.pack_start(self.size_label) 71 | 72 | self.get_button = Gtk.Button.new_from_icon_name("media-playlist-shuffle-symbolic") 73 | self.get_button.connect("clicked",self.on_get_button_clicked) 74 | headerbar.pack_end(self.get_button) 75 | 76 | self.menu_button = Gtk.MenuButton.new() 77 | self.menu_button.set_icon_name("open-menu-symbolic") 78 | headerbar.pack_end(self.menu_button) 79 | 80 | setbackground_action = Gio.SimpleAction.new("background") 81 | setbackground_action.connect("activate",self.on_action_active) 82 | self.add_action(setbackground_action) 83 | setlockscreen_action = Gio.SimpleAction.new("lockscreen") 84 | setlockscreen_action.connect("activate",self.on_action_active) 85 | self.add_action(setlockscreen_action) 86 | download_action = Gio.SimpleAction.new("download") 87 | download_action.connect("activate",self.on_action_active) 88 | self.add_action(download_action) 89 | 90 | menu = Gio.Menu.new() 91 | menu.append("Set as Background","win.background") 92 | menu.append("Set as LockScreen","win.lockscreen") 93 | menu.append("Download","win.download") 94 | menu.append("About","app.about") 95 | menu.append("Quit","app.quit") 96 | self.menu_button.set_menu_model(menu) 97 | 98 | self.__link = "https://source.unsplash.com/random/" 99 | self.msg = Soup.Message.new("GET",self.__link) 100 | self.session = Soup.Session.new() 101 | 102 | listbox = Gtk.ListBox.new() 103 | listbox.props.margin_start = 1 104 | listbox.props.margin_end = 1 105 | self.entry = Adw.EntryRow.new() 106 | listbox.append(self.entry) 107 | self.entry.set_title("Enter Keywords...") 108 | self.entry.set_enable_undo(True) 109 | self.entry.set_max_width_chars(40) 110 | self.mainvbox.append(listbox) 111 | 112 | self.toastoverlay = Adw.ToastOverlay.new() 113 | self.mainvbox.append(self.toastoverlay) 114 | 115 | icon_theme = Gtk.IconTheme.new() 116 | icon_paintable = icon_theme.lookup_icon("image-missing",["image-x-generic","folder-pictures","preferences-desktop-wallpaper"],512,1,self.get_direction(),Gtk.IconLookupFlags.FORCE_SYMBOLIC ) 117 | self.picture = Gtk.Picture.new() 118 | self.picture.set_paintable(icon_paintable ) 119 | 120 | self.picture.add_css_class("osd") 121 | self.picture.props.hexpand = True 122 | self.picture.props.vexpand = True 123 | self.toastoverlay.set_child(self.picture) 124 | 125 | def on_action_active(self,action,p): 126 | if self.current_pixbuf: 127 | file_location_to_save = os.path.join(DOWNLOAD_LOCATION,self.current_pixbuf.__file_name) 128 | if not self.current_pixbuf.savev(file_location_to_save,self.current_pixbuf.__picture_type,None,None): 129 | self.toastoverlay.add_toast(Adw.Toast(title="Save File Faild",timeout=2)) 130 | return 131 | action_name = action.get_name() 132 | if action_name != "download": 133 | with open(file_location_to_save) as wallpaper_file: 134 | self.proxy.get_method("SetWallpaperFile")("",wallpaper_file.fileno(),{"show-preview" : False ,"set-on" : action_name}) 135 | self.toastoverlay.add_toast(Adw.Toast(title="Done",timeout=2)) 136 | 137 | def on_get_button_clicked(self,get_button): 138 | get_button.set_sensitive(False) 139 | keywords = self.entry.get_text().strip() 140 | if keywords: 141 | self.__link = "https://source.unsplash.com/random/?{}".format(keywords) 142 | else: 143 | self.__link = "https://source.unsplash.com/random/" 144 | self.msg = Soup.Message.new("GET",self.__link) 145 | self.session.send_async(self.msg,GLib.PRIORITY_LOW,None,self.on_connect_finish,None) 146 | 147 | def on_connect_finish(self,session, result, data): 148 | try: 149 | input_stream = session.send_finish(result) 150 | self.loader = GdkPixbuf.PixbufLoader.new_with_mime_type(self.msg.props.response_headers.get_content_type()[0]) 151 | self.loader.connect("area_updated",self.on_update) 152 | self.loader.connect("area-prepared",self.on_prepared) 153 | input_stream.read_bytes_async(1024*500,GLib.PRIORITY_HIGH_IDLE ,None,self.on_read_finish) 154 | except Exception as e: 155 | self.get_button.set_sensitive(True) 156 | self.size_label.set_label("") 157 | self.toastoverlay.add_toast(Adw.Toast(title="Connect Faild",timeout=0)) #If timeout is 0, the toast is displayed indefinitely until manually dismissed 158 | print(e) 159 | 160 | def on_read_finish(self,input_stream, result): 161 | try: 162 | chunk = input_stream.read_bytes_finish(result) 163 | if chunk.get_size()>0: 164 | self.loader.write_bytes(chunk) 165 | input_stream.read_bytes_async(1024*500,GLib.PRIORITY_HIGH_IDLE ,None,self.on_read_finish) 166 | else: 167 | self.current_pixbuf = self.loader.get_pixbuf() 168 | self.current_pixbuf.__picture_type = self.msg.props.response_headers.get_one("Content-Type").split("/")[1] 169 | self.current_pixbuf.__file_name = self.msg.props.response_headers.get_one("x-imgix-id")+"."+self.current_pixbuf.__picture_type 170 | self.size_label.set_label("{}X{}".format(self.current_pixbuf.get_width(),self.current_pixbuf.get_height())) 171 | self.loader.close() 172 | input_stream.close() 173 | self.get_button.set_sensitive(True) 174 | except Exception as e: 175 | self.get_button.set_sensitive(True) 176 | self.size_label.set_label("") 177 | self.toastoverlay.add_toast(Adw.Toast(title="Get File Faild",timeout=0)) 178 | print(e) 179 | try: 180 | self.loader.close() 181 | input_stream.close() 182 | except Exception as e: 183 | pass 184 | print(e) 185 | 186 | def on_prepared(self,pixbuf_loader): 187 | pixbuf = pixbuf_loader.get_pixbuf() 188 | pixbuf.fill(0xaaaaaaff) 189 | texture = Gdk.Texture.new_for_pixbuf(pixbuf) 190 | self.picture.set_paintable(texture) 191 | 192 | def on_update(self,pixbuf_loader, x, y, width, height): 193 | pixbuf = pixbuf_loader.get_pixbuf() 194 | texture = Gdk.Texture.new_for_pixbuf(pixbuf) 195 | self.picture.set_paintable(texture) 196 | 197 | class MyApp(Adw.Application): 198 | def __init__(self, **kwargs): 199 | super().__init__(**kwargs) 200 | self.create_action('quit', lambda *_: self.quit(), ['q']) 201 | self.create_action('about', self.on_about_action) 202 | 203 | def do_activate(self): 204 | active_window = self.props.active_window 205 | if active_window: 206 | active_window.present() 207 | else: 208 | self.win = MainWindow(application=self) 209 | self.win.present() 210 | 211 | def on_about_action(self, widget, _): 212 | """Callback for the app.about action.""" 213 | about = Adw.AboutWindow(transient_for=self.props.active_window, 214 | application_name='Pyrandompics', 215 | application_icon='com.github.yucefsourani.pyrandompics', 216 | developer_name='youssef sourani', 217 | version='1.0', 218 | developers=['youssef sourani'], 219 | copyright='© 2023 youssef sourani', 220 | comments = "Get Random Pictures From\nhttps://unsplash.com\n", 221 | license_type = Gtk.License.GPL_3_0 , 222 | website = "https://github.com/yucefsourani/pyrandompics", 223 | issue_url = "https://github.com/yucefsourani/pyrandompics/issues") 224 | about.present() 225 | 226 | def create_action(self, name, callback, shortcuts=None): 227 | """Add an application action. 228 | 229 | Args: 230 | name: the name of the action 231 | callback: the function to be called when the action is 232 | activated 233 | shortcuts: an optional list of accelerators 234 | """ 235 | action = Gio.SimpleAction.new(name, None) 236 | action.connect("activate", callback) 237 | self.add_action(action) 238 | if shortcuts: 239 | self.set_accels_for_action(f"app.{name}", shortcuts) 240 | 241 | app = MyApp(application_id="com.github.yucefsourani.pyrandompics",flags= Gio.ApplicationFlags.FLAGS_NONE) 242 | app.run(sys.argv) 243 | -------------------------------------------------------------------------------- /small_programs/pyscanbc/README.md: -------------------------------------------------------------------------------- 1 | # Using zbar gstreamer plugins to scan BarCode . 2 | 3 | # Requires (available in fedora 39 official repos) 4 | 5 | ``` gstreamer1-plugins-bad-free-zbar ``` 6 | 7 | ``` gstreamer1-plugin-gtk4 ``` 8 | 9 | ``` python3-dbus ``` 10 | 11 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyscanbc/Screenshot.png "Screenshot") 12 | 13 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/pyscanbc/Screenshot1.png "Screenshot") 14 | 15 | 16 | -------------------------------------------------------------------------------- /small_programs/pyscanbc/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyscanbc/Screenshot.png -------------------------------------------------------------------------------- /small_programs/pyscanbc/Screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/pyscanbc/Screenshot1.png -------------------------------------------------------------------------------- /small_programs/pyscanbc/pyscanbc.py: -------------------------------------------------------------------------------- 1 | # pyscanbc.py 2 | # 3 | # Copyright 2023 youssef sourani 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | # SPDX-License-Identifier: GPL-3.0-or-later 19 | # Requires packages gstreamer1-plugins-bad-free-zbar gstreamer1-plugin-gtk4 (in fedora 39 repos) 20 | 21 | import gi 22 | gi.require_version('Gst', '1.0') 23 | gi.require_version('Gtk', '4.0') 24 | gi.require_version('Adw', '1') 25 | from gi.repository import Gst,Gtk,Gio,Adw,GObject,Gdk 26 | import dbus 27 | from dbus.mainloop.glib import DBusGMainLoop 28 | import os 29 | import sys 30 | 31 | 32 | DBusGMainLoop(set_as_default=True) 33 | 34 | Gst.init(None) 35 | 36 | request_iface = 'org.freedesktop.portal.Request' 37 | session_iface = 'org.freedesktop.portal.Session' 38 | 39 | class CProxy(): 40 | def __init__(self,name,object_path,interface_name): 41 | self.__name = name 42 | self.__object_path = object_path 43 | self.__interface_name = interface_name 44 | self.bus = dbus.SessionBus() 45 | 46 | self.__main_object = self.bus.get_object(self.__name,self.__object_path) 47 | self.__props_interface = dbus.Interface(self.__main_object,"org.freedesktop.DBus.Properties") 48 | 49 | self.__token_temp = 0 50 | self.unique_name = self.bus.get_unique_name().replace(":","").replace(".","_") 51 | self.create_token() 52 | 53 | def create_token(self): 54 | self.token = os.path.basename(__file__).replace(":","").replace(".","_")+ str(self.__token_temp) 55 | self.__token_temp += 1 56 | return self.token 57 | 58 | def get_method(self,method_name,interface = None): 59 | if not interface: 60 | interface = self.__interface_name 61 | return self.__main_object.get_dbus_method(method_name,interface) 62 | 63 | def get_props(self,props): 64 | return self.__props_interface.Get(self.__interface_name,props) 65 | 66 | def connect_to_request_response(self,path_name,callback): 67 | return self.bus.add_signal_receiver(handler_function=callback, 68 | bus_name=self.__name, 69 | dbus_interface=request_iface, 70 | signal_name="Response", 71 | path_keyword=path_name) 72 | 73 | 74 | class BarCode(Gtk.Widget): 75 | __gsignals__ = { "barcode" : (GObject.SignalFlags.RUN_LAST, None, (str,)), 76 | "eos" : (GObject.SignalFlags.RUN_LAST, None, ()), 77 | "stopped" : (GObject.SignalFlags.RUN_LAST, None, ()), 78 | "playing" : (GObject.SignalFlags.RUN_LAST, None, ()), 79 | "warning" : (GObject.SignalFlags.RUN_LAST, None, (str,str)), 80 | "error" : (GObject.SignalFlags.RUN_LAST, None, (str,str)), 81 | "permission_camera" : (GObject.SignalFlags.RUN_LAST, None, (bool,)), 82 | "permission_device" : (GObject.SignalFlags.RUN_LAST, None, (bool,)), 83 | "camera_present" : (GObject.SignalFlags.RUN_LAST, None, (bool,)) 84 | } 85 | def __init__(self,parent,temp_icon_file="scanner-symbolic",w=0,h=0): 86 | Gtk.Widget.__init__(self) 87 | self.props.vexpand = True 88 | self.props.hexpand = True 89 | self.__parent = parent 90 | self.w = w 91 | self.h = h 92 | self.__temp_icon_file = temp_icon_file 93 | self.dp = CProxy("org.freedesktop.portal.Desktop","/org/freedesktop/portal/desktop","org.freedesktop.portal.Device") 94 | self.cp = CProxy("org.freedesktop.portal.Desktop","/org/freedesktop/portal/desktop","org.freedesktop.portal.Camera") 95 | 96 | self.player = Gst.parse_launch("pipewiresrc name=pipewiresrc ! videoconvert ! zbar ! videoconvert ! gtk4paintablesink name=gtk4") 97 | self.pipewiresrc = self.player.get_by_name('pipewiresrc') 98 | self.gtk4paintablesink = self.player.get_by_name('gtk4') 99 | self.gtk4paintables = self.gtk4paintablesink.props.paintable 100 | 101 | if self.__temp_icon_file: 102 | self.__use_icon = True 103 | if os.path.isfile(self.__temp_icon_file): 104 | self.__mediafile = Gtk.MediaFile.new_for_filename(self.__temp_icon_file) 105 | self.__mediafile.set_loop(True) 106 | self.__mediafile.play() 107 | else: 108 | icon_theme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default()) 109 | icon = icon_theme.lookup_icon(self.__temp_icon_file,["applications-accessories"],self.w,1, self.__parent.get_direction(), Gtk.IconLookupFlags(1) ) 110 | self.__mediafile = Gtk.MediaFile.new_for_file(icon.props.file) 111 | self.__mediafile.set_loop(True) 112 | self.__mediafile.play() 113 | else: 114 | self.__use_icon = False 115 | self.pipbus = self.player.get_bus() 116 | self.pipbus.add_signal_watch() 117 | self.pipbus.connect("message", self.__bus_call) 118 | 119 | self.gtk4paintables.connect("invalidate_contents",lambda *a : self.queue_draw()) 120 | self.gtk4paintables.connect("invalidate_size",lambda *a : self.queue_draw()) 121 | 122 | 123 | 124 | def init(self): 125 | if self.cp.get_props("IsCameraPresent"): 126 | self.emit("camera_present",True) 127 | self.access_device() 128 | else: 129 | self.emit("camera_present",False) 130 | 131 | def access_device(self): 132 | request = self.dp.get_method("AccessDevice")(os.getpid(),["camera"],{"handle_token": self.dp.create_token()}) 133 | self.dp.last_signal = self.dp.connect_to_request_response(request,self.on_access_device_done) 134 | 135 | def on_access_device_done(self,*aa,**bb): 136 | self.dp.last_signal.remove() 137 | if aa[0] == 0: 138 | self.emit("permission_device",True) 139 | self.access_camera() 140 | else: 141 | self.emit("permission_device",False) 142 | 143 | def do_snapshot(self,snapshot): 144 | if self.w == 0 : 145 | w = self.__parent.get_width() 146 | else: 147 | w = self.w 148 | if self.h == 0 : 149 | h = self.__parent.get_height() 150 | else: 151 | h = self.h 152 | if self.__use_icon : 153 | self.__mediafile.snapshot(snapshot,w,h) 154 | else: 155 | self.gtk4paintables.snapshot(snapshot,w,h) 156 | 157 | def play(self): 158 | self.__use_icon = False 159 | self.player.set_state(Gst.State.PLAYING) 160 | self.emit("playing") 161 | 162 | def stop(self): 163 | if self.__temp_icon_file: 164 | self.__use_icon = True 165 | self.player.set_state(Gst.State.NULL ) 166 | self.emit("stopped") 167 | 168 | def access_camera(self): 169 | request = self.cp.get_method("AccessCamera")({"handle_token": self.cp.create_token()}) 170 | self.cp.last_signal= self.cp.connect_to_request_response(request,self.on_access_camera_done) 171 | 172 | def on_access_camera_done(self,*aa,**bb): 173 | self.cp.last_signal.remove() 174 | if aa[0] == 0: 175 | self.emit("permission_camera",True) 176 | fd = self.cp.get_method("OpenPipeWireRemote")(dict()) 177 | fd = fd.take() 178 | self.pipewiresrc.set_property('fd',fd) 179 | else: 180 | self.emit("permission_camera",False) 181 | 182 | def __bus_call(self,bus, message): 183 | if message.src.get_name() == "zbar0": 184 | barcode = message.get_structure().get_string("symbol") 185 | if barcode : 186 | self.emit("barcode",barcode) 187 | t = message.type 188 | if t == Gst.MessageType.EOS: 189 | self.emit("eos") 190 | elif t == Gst.MessageType.WARNING: 191 | err, debug = message.parse_warning() 192 | self.emit("warning",str(err),str(debug)) 193 | print("warning",str(err),str(debug)) 194 | elif t == Gst.MessageType.ERROR: 195 | err, debug = message.parse_error() 196 | self.emit("error",str(err),str(debug)) 197 | print("error",str(err),str(debug)) 198 | return True 199 | 200 | def do_get_request_mode(self): 201 | return Gtk.SizeRequestMode.CONSTANT_SIZE 202 | 203 | def do_measure(self, orientation, for_size): 204 | if self.w == 0 : 205 | w = self.__parent.get_width() 206 | else: 207 | w = self.w 208 | if self.h == 0 : 209 | h = self.__parent.get_height() 210 | else: 211 | h = self.h 212 | if orientation == Gtk.Orientation.HORIZONTAL: 213 | return (w, w, -1, -1) 214 | else: 215 | return (h, h, -1, -1) 216 | 217 | class pyscanbcWindow(Adw.ApplicationWindow): 218 | __gtype_name__ = 'pyscanbcWindow' 219 | def __init__(self, *args, **kwargs): 220 | super().__init__(*args, **kwargs) 221 | self.maximize() 222 | 223 | mainbox = Gtk.Box.new(orientation = Gtk.Orientation.VERTICAL,spacing=0) 224 | self.set_content(mainbox) 225 | 226 | headerbar = Adw.HeaderBar.new() 227 | headerbar.set_title_widget(Gtk.Label.new("Pyscanbc")) 228 | mainbox.append(headerbar) 229 | 230 | listbox = Gtk.ListBox.new() 231 | listbox.props.margin_start = 1 232 | listbox.props.margin_end = 1 233 | listbox.props.margin_top = 1 234 | listbox.props.margin_bottom = 1 235 | mainbox.append(listbox) 236 | self.result_entry = Adw.EntryRow.new() 237 | 238 | copy_button = Gtk.Button.new_from_icon_name("edit-copy-symbolic") 239 | copy_button.connect("clicked",self.on_copy_button_clicked) 240 | copy_button.add_css_class("flat") 241 | copy_button.add_css_class("osd") 242 | copy_button.add_css_class("circular") 243 | self.result_entry.add_suffix(copy_button) 244 | listbox.append(self.result_entry) 245 | 246 | self.revealer = Gtk.Revealer.new() 247 | self.revealer.set_transition_duration(2000) 248 | mainbox.append(self.revealer) 249 | 250 | self.status_label = Gtk.Label.new() 251 | self.revealer.set_child(self.status_label) 252 | 253 | barcode_box = Gtk.Box.new(orientation = Gtk.Orientation.HORIZONTAL,spacing=0) 254 | mainbox.append(barcode_box) 255 | self.barcode_widget = BarCode(barcode_box) 256 | barcode_box.append(self.barcode_widget) 257 | 258 | self.play_button = Gtk.ToggleButton.new() 259 | self.play_button.props.icon_name = "media-playback-start-symbolic" 260 | self.play_signal_handler = self.play_button.connect("toggled",self.on_toggle_play_button) 261 | mainbox.append(self.play_button) 262 | 263 | self.barcode_widget.connect("camera_present",self.__on_camera_present_check_done) 264 | self.barcode_widget.connect("permission_camera",self.__on_permission_done,"Camera") 265 | self.barcode_widget.connect("permission_device",self.__on_permission_done,"Camera Device") 266 | self.barcode_widget.connect("barcode",self.__on_barcode_detected) 267 | self.barcode_widget.connect("error",self.__on_stopped) 268 | self.barcode_widget.connect("eos",self.__on_stopped) 269 | self.barcode_widget.init() 270 | 271 | def on_copy_button_clicked(self,button): 272 | text = self.result_entry.get_text() 273 | if not text.strip(): 274 | return 275 | clipboard = self.get_clipboard() 276 | clipboard.set_content(Gdk.ContentProvider.new_for_value(text)) 277 | 278 | def on_toggle_play_button(self,play_button): 279 | if not play_button.props.active: 280 | self.barcode_widget.stop() 281 | play_button.props.icon_name = "media-playback-start-symbolic" 282 | else: 283 | self.barcode_widget.play() 284 | play_button.props.icon_name = "media-playback-stop-symbolic" 285 | 286 | def __on_camera_present_check_done(self,barcode_widget,iscamerapresent): 287 | if not iscamerapresent: 288 | self.status_label.props.label = "Camera Is Not Present" 289 | self.status_label.add_css_class("error") 290 | self.revealer.props.reveal_child = True 291 | self.play_button.set_sensitive(False) 292 | 293 | def __on_barcode_detected(self,barcode_widget,barcode_text): 294 | print(barcode_text) 295 | self.result_entry.set_text(barcode_text) 296 | self.play_button.set_active(False) 297 | 298 | def __on_stopped(self,barcode_widget,error=None,debug=None): 299 | self.play_button.set_active(False) 300 | 301 | def __on_permission_done(self,barcode_widget,permission,name): 302 | if not permission: 303 | self.play_button.set_sensitive(False) 304 | self.status_label.props.label = "{} Permission Denied".format(name) 305 | self.status_label.add_css_class("error") 306 | self.revealer.props.reveal_child = True 307 | 308 | class MyApp(Adw.Application): 309 | def __init__(self, **kwargs): 310 | super().__init__(**kwargs) 311 | 312 | def do_activate(self): 313 | active_window = self.props.active_window 314 | if active_window: 315 | active_window.present() 316 | else: 317 | self.win = pyscanbcWindow(application=self) 318 | self.win.present() 319 | 320 | if __name__ == "__main__": 321 | app = MyApp(application_id="com.github.yucefsourani.pyscanbc",flags= Gio.ApplicationFlags.FLAGS_NONE) 322 | app.run(sys.argv) 323 | -------------------------------------------------------------------------------- /small_programs/timer/README.md: -------------------------------------------------------------------------------- 1 | # Simple Timer 2 | 3 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/timer/Screenshot.png "Screenshot") 4 | 5 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/small_programs/timer/Screenshot1.png "Screenshot") 6 | 7 | 8 | -------------------------------------------------------------------------------- /small_programs/timer/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/timer/Screenshot.png -------------------------------------------------------------------------------- /small_programs/timer/Screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/small_programs/timer/Screenshot1.png -------------------------------------------------------------------------------- /small_programs/timer/timer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # 4 | # Copyright 2023 yucef sourani 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software 18 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 | # MA 02110-1301, USA. 20 | # 21 | # 22 | import sys 23 | import gi 24 | gi.require_version('Gtk', '4.0') 25 | gi.require_version('Adw', '1') 26 | from gi.repository import Gtk,Gio,GLib,Gdk,Adw 27 | import time 28 | 29 | 30 | # https://gnome.pages.gitlab.gnome.org/libadwaita/doc/main/style-classes.html 31 | css = b""" 32 | #startrecordbutton { 33 | padding: 40px; 34 | color: @accent_bg_color; 35 | background-color: @accent_bg_color; 36 | box-shadow: 0px 1px 1px 0px @accent_bg_color, 0px 1px 2px 0px @accent_bg_color, inset 0 0 0 1px @accent_bg_color; 37 | } 38 | 39 | #stoprecordbutton { 40 | padding: 40px; 41 | color: @destructive_bg_color; 42 | background-color: @destructive_bg_color; 43 | box-shadow: 0px 1px 1px 0px @destructive_bg_color, 0px 1px 2px 0px @destructive_bg_color, inset 0 0 0 1px @destructive_bg_color; 44 | } 45 | 46 | """ 47 | 48 | 49 | class MainWindow(Adw.ApplicationWindow): 50 | def __init__(self, *args, **kwargs): 51 | super().__init__(*args, **kwargs) 52 | #self.set_default_size(600, 400) 53 | style_provider = Gtk.CssProvider() 54 | style_provider.load_from_data(css) 55 | Gtk.StyleContext.add_provider_for_display(Gdk.Display().get_default(), 56 | style_provider, 57 | Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 58 | self.mainvbox = Gtk.Box.new(orientation = Gtk.Orientation.VERTICAL,spacing = 0) 59 | self.set_content(self.mainvbox) 60 | 61 | headerbar = Gtk.HeaderBar.new() 62 | headerbar.set_title_widget(Gtk.Label.new("Timer")) 63 | self.mainvbox.append(headerbar) 64 | 65 | self.menu_button = Gtk.MenuButton.new() 66 | self.menu_button.set_icon_name("open-menu-symbolic") 67 | headerbar.pack_end(self.menu_button) 68 | 69 | menu = Gio.Menu.new() 70 | menu.append("About","app.about") 71 | menu.append("Quit","app.quit") 72 | self.menu_button.set_menu_model(menu) 73 | 74 | clamp = Adw.Clamp.new() 75 | self.mainvbox.append(clamp) 76 | clamp.set_halign(Gtk.Align.CENTER) 77 | clamp.set_valign(Gtk.Align.CENTER) 78 | clamp.props.hexpand = True 79 | clamp.props.vexpand = True 80 | clamp.set_maximum_size(600) 81 | 82 | frame = Gtk.Frame.new() 83 | frame.props.margin_top = 5 84 | frame.props.margin_bottom = 5 85 | frame.props.margin_start = 5 86 | frame.props.margin_end = 5 87 | clamp.set_child(frame) 88 | frame.add_css_class("card") 89 | 90 | framebox = Gtk.Box.new(orientation = Gtk.Orientation.VERTICAL,spacing = 15) 91 | frame.set_child(framebox) 92 | 93 | self.start_stop_timer_button = Gtk.Button.new() 94 | self.start_stop_timer_button.set_name("startrecordbutton") 95 | self.start_stop_timer_button.props.margin_top = 50 96 | self.start_stop_timer_button.props.margin_bottom = 10 97 | self.start_stop_timer_button.set_halign(Gtk.Align.CENTER) 98 | self.start_stop_timer_button.set_valign(Gtk.Align.CENTER) 99 | self.start_stop_timer_button.add_css_class("circular") 100 | self.start_stop_timer_button.add_css_class("flat") 101 | self.start_stop_timer_button.connect("clicked",self.on_start_stop_button_clicked) 102 | framebox.append(self.start_stop_timer_button) 103 | 104 | self.time_label = Gtk.Label.new() 105 | self.time_label.add_css_class("title-2") 106 | self.time_label.props.margin_top = 30 107 | self.time_label.props.margin_bottom = 50 108 | self.time_label.set_halign(Gtk.Align.CENTER) 109 | self.time_label.set_valign(Gtk.Align.CENTER) 110 | self.time_label.props.label = "00:00:00" 111 | framebox.append(self.time_label) 112 | 113 | def change_time(self): 114 | self.time_label.props.label = time.strftime("%H:%M:%S",time.gmtime(time.time() - self.old_time)) 115 | return True # return True to continue false to break timeout_add 116 | 117 | def on_start_stop_button_clicked(self,button): 118 | if button.get_name() == "startrecordbutton": 119 | button.set_name("stoprecordbutton") 120 | self.old_time = time.time() 121 | self.source_tag = GLib.timeout_add(500,self.change_time) 122 | else: 123 | GLib.source_remove(self.source_tag) 124 | button.set_name("startrecordbutton") 125 | 126 | class MyApp(Adw.Application): 127 | def __init__(self, **kwargs): 128 | super().__init__(**kwargs) 129 | self.create_action('quit', lambda *_: self.quit(), ['q']) 130 | self.create_action('about', self.on_about_action) 131 | 132 | def do_activate(self): 133 | active_window = self.props.active_window 134 | if active_window: 135 | active_window.present() 136 | else: 137 | self.win = MainWindow(application=self) 138 | self.win.present() 139 | 140 | def on_about_action(self, widget, _): 141 | """Callback for the app.about action.""" 142 | about = Adw.AboutWindow(transient_for=self.props.active_window, 143 | application_name='Timer', 144 | application_icon='com.github.yucefsourani.python-gtk4-examples', 145 | developer_name='youssef sourani', 146 | version='1.0', 147 | developers=['youssef sourani'], 148 | copyright='© 2023 youssef sourani', 149 | comments = "Timer", 150 | license_type = Gtk.License.GPL_3_0 , 151 | website = "https://github.com/yucefsourani/python-gtk4-examples", 152 | issue_url = "https://github.com/yucefsourani/python-gtk4-examples/issues") 153 | about.present() 154 | 155 | def create_action(self, name, callback, shortcuts=None): 156 | """Add an application action. 157 | 158 | Args: 159 | name: the name of the action 160 | callback: the function to be called when the action is 161 | activated 162 | shortcuts: an optional list of accelerators 163 | """ 164 | action = Gio.SimpleAction.new(name, None) 165 | action.connect("activate", callback) 166 | self.add_action(action) 167 | if shortcuts: 168 | self.set_accels_for_action(f"app.{name}", shortcuts) 169 | 170 | app = MyApp(application_id="com.github.yucefsourani.python-gtk4-examples",flags= Gio.ApplicationFlags.FLAGS_NONE) 171 | app.run(sys.argv) 172 | -------------------------------------------------------------------------------- /spinner/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Spinner 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio,GLib 8 | import threading 9 | import time 10 | 11 | class MainWindow(Gtk.ApplicationWindow): 12 | def __init__(self, *args, **kwargs): 13 | super().__init__(*args, **kwargs) 14 | self.app_ = self.get_application() 15 | 16 | self.headerbar = Gtk.HeaderBar.new() 17 | self.set_titlebar(self.headerbar) 18 | 19 | self.spinner = Gtk.Spinner.new() 20 | self.headerbar.pack_end(self.spinner) 21 | 22 | start_button = Gtk.Button.new() 23 | start_button.props.label = "Start Task" 24 | start_button.connect("clicked",self.on_start_button_clicked) 25 | self.set_child(start_button) 26 | 27 | def on_start_button_clicked(self,start_button): 28 | threading.Thread(target=self.__thread_on_start_button_clicked,args=(start_button,)).start() 29 | 30 | def __thread_on_start_button_clicked(self,start_button): 31 | #self.spinner.start() 32 | GLib.idle_add(self.spinner.start) # use GLib.idle_add to run gtk method from another thread 33 | 34 | GLib.idle_add(start_button.set_sensitive,False) # Disable Start Task Button 35 | 36 | for i in range(5):# timeout for 5 second 37 | time.sleep(1) 38 | 39 | #self.spinner.stop() 40 | GLib.idle_add(self.spinner.stop) # use GLib.idle_add to run gtk method from another thread 41 | 42 | GLib.idle_add(start_button.set_sensitive,True) # Enable Start Task Button 43 | 44 | class MyApp(Gtk.Application): 45 | def __init__(self, **kwargs): 46 | super().__init__(**kwargs) 47 | 48 | def do_activate(self): 49 | active_window = self.props.active_window 50 | if active_window: 51 | active_window.present() 52 | else: 53 | self.win = MainWindow(application=self) 54 | self.win.present() 55 | 56 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 57 | app.run(sys.argv) 58 | ``` 59 | 60 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/spinner/Screenshot.png "Screenshot") 61 | 62 | [Gtk.Spinner](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Spinner.html) 63 | -------------------------------------------------------------------------------- /spinner/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/spinner/Screenshot.png -------------------------------------------------------------------------------- /stack/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Stack 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | self.set_default_size(400, 200) 14 | 15 | self.headerbar = Gtk.HeaderBar.new() 16 | self.set_titlebar(self.headerbar) 17 | add_random_label_button = Gtk.Button.new_from_icon_name("list-add-symbolic") 18 | add_random_label_button.connect("clicked",self.on_add_random_label_button_clicked) 19 | add_random_label_button.set_tooltip_text("Add Random Label") 20 | self.headerbar.pack_start(add_random_label_button) 21 | 22 | self.main_box = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,0) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 23 | self.set_child(self.main_box) 24 | 25 | 26 | self.stack = Gtk.Stack.new() 27 | self.stack.props.hexpand = True 28 | self.stack.props.vexpand = True 29 | categories = ("Internet","Graphics") 30 | 31 | for category in categories: 32 | sw = Gtk.ScrolledWindow.new() 33 | box = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) 34 | sw.set_child(box) 35 | self.stack.add_titled(sw,category,category) # Widget,name,title to show in Gtk.StackSidebar 36 | 37 | stack_switcher_sidebar = Gtk.StackSidebar.new() 38 | stack_switcher_sidebar.props.hexpand = False 39 | stack_switcher_sidebar.props.vexpand = False 40 | stack_switcher_sidebar.set_stack(self.stack) 41 | 42 | self.main_box.append(stack_switcher_sidebar) 43 | self.main_box.append(self.stack) 44 | 45 | def on_add_random_label_button_clicked(self,button): 46 | visible_box = self.stack.get_visible_child().get_child().get_child() # Gtk.ScrolledWindow ===> get_child ====> Gtk.Viewport ===> get_child ====> Gtk.Box 47 | visible_child_name = self.stack.get_visible_child_name() # name look at self.stack.add_titled 48 | print(visible_box) 49 | print(visible_child_name) 50 | 51 | visible_box.append(Gtk.Label.new(visible_child_name)) 52 | 53 | class MyApp(Gtk.Application): 54 | def __init__(self, **kwargs): 55 | super().__init__(**kwargs) 56 | 57 | def do_activate(self): 58 | active_window = self.props.active_window 59 | if active_window: 60 | active_window.present() 61 | else: 62 | self.win = MainWindow(application=self) 63 | self.win.present() 64 | 65 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 66 | app.run(sys.argv) 67 | ``` 68 | 69 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/stack/Screenshot.png "Screenshot") 70 | 71 | [Gtk.Stack](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Stack.html) 72 | -------------------------------------------------------------------------------- /stack/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack/Screenshot.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.FlowBox 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio,Gdk 8 | 9 | css = b""" 10 | .h1 { 11 | font-size: 24px; 12 | } 13 | .h2 { 14 | font-weight: 300; 15 | font-size: 18px; 16 | } 17 | .h3 { 18 | font-size: 11px; 19 | } 20 | .h4 { 21 | color: alpha (@text_color, 0.7); 22 | font-weight: bold; 23 | text-shadow: 0 1px @text_shadow_color; 24 | } 25 | """ 26 | 27 | class MainWindow(Gtk.ApplicationWindow): 28 | def __init__(self, *args, **kwargs): 29 | super().__init__(*args, **kwargs) 30 | self.app_ = self.get_application() 31 | self.set_default_size(600, 400) 32 | 33 | style_provider = Gtk.CssProvider() 34 | style_provider.load_from_data(css) 35 | Gtk.StyleContext.add_provider_for_display(Gdk.Display().get_default(), 36 | style_provider, 37 | Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 38 | 39 | self.main_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 40 | self.set_child(self.main_box) 41 | 42 | self.stack = Gtk.Stack.new() 43 | self.stack.props.hexpand = True 44 | self.stack.props.vexpand = True 45 | data_and_categories = { 46 | ("Firefox" ,"Web Browser" ,"icons_folder/appicns_Firefox.png") : "Internet", 47 | ("Chromium","Web Browser" ,"icons_folder/Chromium_logo.png") : "Internet", 48 | ("Brave" ,"Web Browser" ,"icons_folder/brave.png") : "Internet", 49 | ("Opera" ,"Web Browser" ,"icons_folder/Opera-logo-256x256.png") : "Internet", 50 | ("Vivaldi" ,"Web Browser" ,"icons_folder/vivaldi.png") : "Internet", 51 | ("Gimp" ,"Image Manipulation" ,"icons_folder/gimp.png") : "Graphics", 52 | ("Inkscape","svg Editor..." ,"icons_folder/inkscape.png") : "Graphics", 53 | ("Krita" ,"sketching and painting","icons_folder/krita.png") : "Graphics", 54 | ("Blender" ,"3D modeling..." ,"icons_folder/Blender-icon.png") : "Graphics", 55 | ("Kdenlive","Video Editor..." ,"icons_folder/kdenlive.png") : "Graphics" 56 | } 57 | done = [] 58 | for data,category in data_and_categories.items(): 59 | if category not in done: # if flowbox not exist in stack 60 | sw = Gtk.ScrolledWindow.new() 61 | flowbox = Gtk.FlowBox.new() 62 | sw.set_child(flowbox) 63 | flowbox.props.homogeneous = True 64 | flowbox.set_valign(Gtk.Align.START) # top to bottom 65 | flowbox.props.margin_start = 20 66 | flowbox.props.margin_end = 20 67 | flowbox.props.margin_top = 20 68 | flowbox.props.margin_bottom = 20 69 | flowbox.props.hexpand = True 70 | flowbox.props.vexpand = True 71 | flowbox.props.max_children_per_line = 4 72 | flowbox.props.selection_mode = Gtk.SelectionMode.NONE 73 | self.stack.add_titled(sw,category,category) # Widget,name,title to show in Gtk.StackSidebar 74 | done.append(category) 75 | else: # if flowbox already exist in stack 76 | flowbox = self.stack.get_child_by_name(category).get_child().get_child() #Gtk.ScrolledWindow ===> get_child ====> Gtk.Viewport ===> get_child ====> Gtk.FlowBox 77 | 78 | 79 | icon_vbox = Gtk.Box.new( Gtk.Orientation.VERTICAL,0) 80 | 81 | icon = Gtk.Image.new_from_file(data[2])#data[2] icons_folder/appicns_Firefox.png and ... 82 | icon.set_icon_size(Gtk.IconSize.LARGE) 83 | # https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Image.html 84 | icon_vbox.append(icon) 85 | 86 | name_label = Gtk.Label.new(data[0]) #Firefox and .... 87 | name_label.add_css_class("h1") # look at css 88 | icon_vbox.append(name_label) 89 | 90 | summary_label = Gtk.Label.new(data[1]) #Web Browser and .... 91 | summary_label.add_css_class("h3") #look at css 92 | icon_vbox.append(summary_label) 93 | 94 | button = Gtk.Button.new() 95 | button.set_has_frame(False) 96 | button.set_child(icon_vbox) 97 | flowbox.append(button) 98 | button.connect("clicked",self.on_button_clicked,data[0]) 99 | 100 | 101 | 102 | stack_switcher = Gtk.StackSwitcher.new() 103 | stack_switcher.props.hexpand = False 104 | stack_switcher.props.vexpand = False 105 | stack_switcher.set_stack(self.stack) 106 | 107 | self.main_box.append(stack_switcher) 108 | self.main_box.append(self.stack) 109 | 110 | def on_button_clicked(self,button,programename): 111 | print(programename) 112 | 113 | class MyApp(Gtk.Application): 114 | def __init__(self, **kwargs): 115 | super().__init__(**kwargs) 116 | 117 | def do_activate(self): 118 | active_window = self.props.active_window 119 | if active_window: 120 | active_window.present() 121 | else: 122 | self.win = MainWindow(application=self) 123 | self.win.present() 124 | 125 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 126 | app.run(sys.argv) 127 | ``` 128 | 129 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/stack_flowbox_css_provider/Screenshot.png "Screenshot") 130 | 131 | [Gtk.FlowBox](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/FlowBox.html) 132 | 133 | [Gtk.Stack](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Stack.html) 134 | 135 | [Gtk.Image](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Image.html) 136 | 137 | [Gtk.CssProvider](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/CssProvider.html) 138 | 139 | [Gtk.StyleContext](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/StyleContext.html) 140 | -------------------------------------------------------------------------------- /stack_flowbox_css_provider/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/Screenshot.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/Blender-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/Blender-icon.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/Chromium_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/Chromium_logo.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/Opera-logo-256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/Opera-logo-256x256.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/appicns_Firefox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/appicns_Firefox.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/brave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/brave.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/gimp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/gimp.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/inkscape.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/inkscape.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/kdenlive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/kdenlive.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/krita.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/krita.png -------------------------------------------------------------------------------- /stack_flowbox_css_provider/icons_folder/vivaldi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/stack_flowbox_css_provider/icons_folder/vivaldi.png -------------------------------------------------------------------------------- /switch/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Switch 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) 15 | self.set_child(self.main_vertical_box) 16 | 17 | hbox = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,10) 18 | self.main_vertical_box.append(hbox) 19 | 20 | 21 | spinner = Gtk.Spinner.new() 22 | hbox.append(spinner) 23 | 24 | switch = Gtk.Switch.new() 25 | switch.connect("notify::active",self.on_switch_active_changed,spinner) # notify when (active propertie) changed 26 | hbox.append(switch) 27 | 28 | def on_switch_active_changed(self,switch,property_,spinner): 29 | is_active = switch.props.active # or switch.get_property(property_.name) # return True Or False 30 | if is_active: 31 | spinner.start() 32 | else: 33 | spinner.stop() 34 | 35 | class MyApp(Gtk.Application): 36 | def __init__(self, **kwargs): 37 | super().__init__(**kwargs) 38 | 39 | def do_activate(self): 40 | active_window = self.props.active_window 41 | if active_window: 42 | active_window.present() 43 | else: 44 | self.win = MainWindow(application=self) 45 | self.win.present() 46 | 47 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 48 | app.run(sys.argv) 49 | ``` 50 | 51 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/switch/Screenshot.png "Screenshot") 52 | 53 | [Gtk.Switch](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Switch.html) 54 | -------------------------------------------------------------------------------- /switch/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/switch/Screenshot.png -------------------------------------------------------------------------------- /togglebutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.ToggleButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) #(orientation VERTICAL|HORIZONTAL , spacing in pixels) 15 | self.set_child(self.main_vertical_box) 16 | 17 | spinner1 = Gtk.Spinner.new() 18 | self.main_vertical_box.append(spinner1) 19 | 20 | self.start_stop_spinner1_button = Gtk.ToggleButton.new_with_label("Start/Stop Spinner1") 21 | self.start_stop_spinner1_button.connect("toggled",self.on_start_stop_spinner_button_toggled,spinner1) 22 | self.main_vertical_box.append(self.start_stop_spinner1_button) 23 | 24 | 25 | self.main_vertical_box.append(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL)) 26 | 27 | spinner2 = Gtk.Spinner.new() 28 | self.main_vertical_box.append(spinner2) 29 | 30 | spinner2_hbox = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,1) 31 | self.main_vertical_box.append(spinner2_hbox) 32 | 33 | self.start_spinner2_button = Gtk.ToggleButton.new_with_label("Start Spinner2") 34 | self.start_spinner2_button.props.hexpand = True # to horizontal expand 35 | self.start_spinner2_button.connect("toggled",self.on_start_stop_spinner_button_toggled,spinner2) 36 | spinner2_hbox.append(self.start_spinner2_button) 37 | 38 | self.stop_spinner2_button = Gtk.ToggleButton.new_with_label("Stop Spinner2") 39 | spinner2_hbox.append(self.stop_spinner2_button) 40 | 41 | self.start_spinner2_button.set_group(self.stop_spinner2_button) 42 | 43 | 44 | def on_start_stop_spinner_button_toggled(self,start_stop_spinner_button,spinner): 45 | if start_stop_spinner_button.get_active(): 46 | spinner.start() 47 | else: 48 | spinner.stop() 49 | 50 | 51 | class MyApp(Gtk.Application): 52 | def __init__(self, **kwargs): 53 | super().__init__(**kwargs) 54 | 55 | def do_activate(self): 56 | active_window = self.props.active_window 57 | if active_window: 58 | active_window.present() 59 | else: 60 | self.win = MainWindow(application=self) 61 | self.win.present() 62 | 63 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 64 | app.run(sys.argv) 65 | ``` 66 | 67 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/togglebutton/Screenshot.png "Screenshot") 68 | 69 | [Gtk.ToggleButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/ToggleButton.html) 70 | -------------------------------------------------------------------------------- /togglebutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/togglebutton/Screenshot.png -------------------------------------------------------------------------------- /volumebutton/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.VolumeButton 2 | 3 | ```python 4 | import sys 5 | import gi 6 | gi.require_version('Gtk', '4.0') 7 | from gi.repository import Gtk,Gio 8 | 9 | class MainWindow(Gtk.ApplicationWindow): 10 | def __init__(self, *args, **kwargs): 11 | super().__init__(*args, **kwargs) 12 | self.app_ = self.get_application() 13 | 14 | self.main_vertical_box = Gtk.Box.new( Gtk.Orientation.VERTICAL,10) 15 | self.set_child(self.main_vertical_box) 16 | 17 | hbox = Gtk.Box.new( Gtk.Orientation.HORIZONTAL,10) 18 | hbox.props.margin_start = 20 19 | hbox.props.margin_end = 20 20 | hbox.props.margin_top = 20 21 | hbox.props.margin_bottom = 20 22 | #https://lazka.github.io/pgi-docs/index.html#Gtk-4.0/classes/Widget.html#Gtk.Widget.props.margin_bottom 23 | self.main_vertical_box.append(hbox) 24 | 25 | volumebutton = Gtk.VolumeButton.new() 26 | volumebutton.connect("value-changed",self.on_volume_value_changed) 27 | hbox.append(volumebutton) 28 | 29 | def on_volume_value_changed(self,volumebutton,value): 30 | print(value) 31 | 32 | class MyApp(Gtk.Application): 33 | def __init__(self, **kwargs): 34 | super().__init__(**kwargs) 35 | 36 | def do_activate(self): 37 | active_window = self.props.active_window 38 | if active_window: 39 | active_window.present() 40 | else: 41 | self.win = MainWindow(application=self) 42 | self.win.present() 43 | 44 | app = MyApp(application_id="com.github.yucefsourani.myapplicationexample",flags= Gio.ApplicationFlags.FLAGS_NONE) 45 | app.run(sys.argv) 46 | ``` 47 | 48 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/volumebutton/Screenshot.png "Screenshot") 49 | 50 | [Gtk.VolumeButton](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/VolumeButton.html) 51 | -------------------------------------------------------------------------------- /volumebutton/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/volumebutton/Screenshot.png -------------------------------------------------------------------------------- /window/README.md: -------------------------------------------------------------------------------- 1 | # Gtk.Window 2 | 3 | ```python 4 | import gi 5 | gi.require_version("Gtk", "4.0") 6 | from gi.repository import Gtk, GLib 7 | 8 | QUIT = False 9 | 10 | def quit_(window): 11 | global QUIT 12 | QUIT = True 13 | 14 | class MainWindow(Gtk.Window): 15 | def __init__(self): 16 | super().__init__() 17 | 18 | window = MainWindow() 19 | window.connect("close-request", quit_) 20 | window.show() 21 | 22 | loop = GLib.MainContext().default() 23 | while not QUIT: 24 | loop.iteration(True) 25 | ``` 26 | 27 | ![Alt text](https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/main/window/Screenshot_1.png "Screenshot") 28 | 29 | 30 | 31 | [Gtk.WIndow](https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Window.html) 32 | -------------------------------------------------------------------------------- /window/Screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yucefsourani/python-gtk4-examples/0938277bd9391bd549592e324270bb3f0c7d3cbf/window/Screenshot_1.png --------------------------------------------------------------------------------