简体   繁体   中英

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM