Monday, April 21, 2025

Tkinter Buttons - Run External Apps from Tkinter

So far soo good. Now we will import os module to have access to system commands:

from tkinter import *
import tkinter.messagebox as mb
import os

 Again we need a main window and geometry:

top_win = Tk()
top_win.geometry("500x500")

Now we are creating 3 independent functions.

First function will ping google.com, or any other domain you like: 

def run_ping():
    os.system("ping google.com")

Second function will run Windows Calculator:

def run_calc():
    os.system("calc")

Third function will run Notepad:

def run_notepad():
    os.system("notepad")

All those functions must have corresponding buttons. Don't forget to set command= to appropriate functions we created. 

Also, for every button we must position it using x and y coordinates. You can experiment with pixel values, those I have in source code works for me:

but_1 = Button(top_win, text = "Ping Google", command = run_ping)
but_1.place(x = 5, y = 5)

but_2 = Button(top_win, text = "Calc", command = run_calc)
but_2.place(x = 82, y = 5)

but_3 = Button(top_win, text = "Notepad", command = run_notepad)
but_3.place(x = 118, y = 5)

Don't forget mainloop at the end of code:

top_win.mainloop()

This is full working script:

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("500x500")

def run_ping():
    os.system("ping google.com")

def run_calc():
    os.system("calc")

def run_notepad():
    os.system("notepad")
    

but_1 = Button(top_win, text = "Ping Google", command = run_ping)
but_1.place(x = 5, y = 5)

but_2 = Button(top_win, text = "Calc", command = run_calc)
but_2.place(x = 82, y = 5)

but_3 = Button(top_win, text = "Notepad", command = run_notepad)
but_3.place(x = 118, y = 5)

top_win.mainloop()


No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...