Is there any way to change button color after doing process like if condition in tkinter?

Viewed 84

I'm trying to create a tool that help me to my work, so I want to change the button color to green if ping is successful and unsuccessful if not.

from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import os

window = Tk()
window.geometry("500x500")
window.title("ping Tool")

def ping(*branch):
    for ip in branch:
        response = os.popen(f"ping {ip}").read()
        if "Received = 4" in response:
            print(f"up {ip} Ping Successful")
        else:
            print(f"Down {ip} Ping Unsuccessful")

def ping201():
    ping('4.2.2.2')

def ping202():
    ping('8.8.8.8')

button = ttk.Button(window, text='branch1', command=ping201)
button.grid(row=0, column=0)

button = ttk.Button(window,text='branch2',command=ping202)
button.grid(row=1, column=0)

button = ttk.Button(window,text='Exit',command=window.quit)
button.grid(pady=20)


window.mainloop()
1 Answers

You can achieve this by using closures. Closures are functions defined within other functions. The outer function inherits the variable scope to the inner function. Thus, allowing us to store a specific state only available and specific to every new instance of the inner function.

For each assignment of command=ping(...) a newly defined inner function (closure) is returned. The value of button and *branch is specific to every new instance of onCommand.

For details, see Python's LEGB rule (local, enclosing, global and built-in): https://realpython.com/python-scope-legb-rule/

The background color itself can be changed using button.config(background='green').

from tkinter import *
import os

window = Tk()
window.geometry("500x500")
window.title("ping Tool")

def ping(button, *branch):
    def onCommand():
        for ip in branch:
            response = os.popen(f"ping {ip}").read()
            if "Received = 4" in response:
                print(f"up {ip} Ping Successful")
                button.config(background='green')
            else:
                print(f"Down {ip} Ping Unsuccessful")
                button.config(background='red')
    return onCommand

button = Button(window, text='branch1')
button.config(command=ping(button, '4.2.2.2'))
button.grid(row=0, column=0)

button = Button(window,text='branch2')
button.config(command=ping(button, '8.8.8.8'))
button.grid(row=1, column=0)

button = Button(window,text='Exit',command=window.quit)
button.grid(pady=20)

window.mainloop()
Related