Jan-20-2021, 06:32 PM
What do you think my_btn is after this code executes? If you don't know you should find out.
my_btn = Button(root, text = "CLICK ME", command = my_fun).pack()Classes are a good idea for GUI applications because they combine functions with a private namespace that holds all the related variables. It makes for a very clean solution. But classes are not required. Below is an example that passes the required information as an argument to the callback.
import random from tkinter import * colors = ['red', 'green', 'blue', 'orange', 'yellow'] def my_fun(button): button['fg'] = random.choice(colors) root = Tk() b1 = Button(root, text = "CLICK ME") b1.configure(command = lambda : my_fun(b1)) b1.pack() b2 = Button(root, text = "ME TOO") b2.configure(command = lambda : my_fun(b2)) b2.pack()