0

I'm learning python 3.7 and tkinter.

I want the function to know the name of the button that called it.

from tkinter import *
from random import randint
import inspect

def nay():
    caller = inspect.stack()[1][3] # doesn't work
    caller["text"] = "no"

def yay():
    caller = inspect.stack()[1][3] # doesn't work
    caller["text"] = "yes"

window = Tk()

randno = randint(0,1)
if randno ==1 :
    b1Sel = yay
    b2Sel = nay
else:
    b1Sel = nay
    b2Sel = yay

b1 = Button(window, text="???", command=b1Sel, width=10, height=5, font=font)
b2 = Button(window, text="???", command=b2Sel, width=10, height=5, font=font)
b1.pack(side=LEFT, padx=0)
b2.pack(side=RIGHT, padx=0)

window.mainloop()

I want to create a function that can distinguish which button called it.

Lunartist
  • 394
  • 1
  • 3
  • 9

1 Answers1

-1

One way to do is by using using lambda function

b1 = Button(window, text="A", command=lambda: action(1), width=10, height=5)

Try this code:

def action(num):
    print(num)

b1 = Button(window, text="A", command=lambda: action(1), width=10, height=5)
b2 = Button(window, text="B", command=lambda: action(2), width=10, height=5)
Yash
  • 3,438
  • 2
  • 17
  • 33