Search code examples
terminalpythongtk3

Execute terminal commands using python gtk


I want to make a quick app using gtk and python that when a button is clicked it executes a terminal command. Anyway I can achieve this?


Solution

  • You can follow this tutorial for Python and Gtk. The second example in the tutorial shows how to create a window with a button so to run a command you just need to change the on_button_clicked callback. You can use either os.system or the subprocess module to run commands with Python.

    So to run ls for example:

    import subprocess
    import gi
    
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk
    
    
    class MyWindow(Gtk.Window):
        def __init__(self):
            Gtk.Window.__init__(self, title="Hello World")
    
            self.button = Gtk.Button(label="Click Here")
            self.button.connect("clicked", self.on_button_clicked)
            self.add(self.button)
    
        def on_button_clicked(self, widget):
            subprocess.run(["ls"])
    
    
    win = MyWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()