首页 > 解决方案 > 我如何知道调用当前函数的按钮的名称?

问题描述

我正在学习 python 3.7 和 tkinter。

我希望函数知道调用它的按钮的名称。

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()

我想创建一个可以区分哪个按钮调用它的函数。

标签: pythonbuttontkinter

解决方案


一种方法是使用 lambda 函数

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

试试这个代码:

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)

推荐阅读