如何知道调用当前函数的按钮的名称?

2024-09-27 21:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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()

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


Tags: 函数textfromimporttkinterwindow按钮font
1条回答
网友
1楼 · 发布于 2024-09-27 21:34:18

一种方法是使用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)

相关问题 更多 >

    热门问题