Запуск подпроцесса и привязка обратного вызова к кнопке tkinter - это две разные вещи;
Сначала я расскажу о связывании обратного вызова: здесь мы будем печатать launching 1
в консоли при нажатии кнопки.
import os
import subprocess
import tkinter as tk
def launch_1(): # function to be called
print('launching 1')
root = tk.Tk()
root.geometry('750x650')
root.title('Launch Test')
button1 = tk.Button(root, text="Button1", command=launch_1) # calling from here when button is pressed
button1.pack(side='left', fill='both')
root.mainloop()
Вывод:
launching 1
Теперь давайте запустим подпроцесс;например переполнение стека пинга.
пример взят здесь.
import os
import subprocess
import tkinter as tk
def launch_1():
print('launching 1') # subprocess to ping host launched here after
p1 = subprocess.Popen(['ping', '-c 2', host], stdout=subprocess.PIPE)
output = p1.communicate()[0]
print(output)
root = tk.Tk()
root.geometry('750x650')
root.title('Launch Test')
button1 = tk.Button(root, text="Button1", command=launch_1)
button1.pack(side='left', fill='both')
host = "www.stackoverflow.com" # host to be pinged
root.mainloop()
Вывод теперь:
launching 1
b'PING stackoverflow.com (151.101.65.69): 56 data bytes\n64 bytes from 151.101.65.69: icmp_seq=0 ttl=59 time=166.105 ms\n64 bytes from 151.101.65.69: icmp_seq=1 ttl=59 time=168.452 ms\n\n--- stackoverflow.com ping statistics ---\n2 packets transmitted, 2 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 166.105/167.279/168.452/1.173 ms\n'
Youможете добавить больше кнопок с большим количеством действий по вашему желанию.