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()
我想创建一个可以区分哪个按钮调用它的函数。
解决方案
一种方法是使用 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)
推荐阅读
- swift - SwiftUI - 检测 TabView 上的点击以滚动到列表顶部
- kubernetes - 卷写入权限
- javascript - 为什么对变量执行操作会影响 Vanilla JS 中的 DOM?
- java - 使用 RandomAccessFile 读取文件属性
- c++ - CMake:将可执行文件链接到多个库 (*.so)
- python - 排序算法的时间复杂度
- xcode - QtCreator 问题选项卡为空
- java - 如何在 Spring Boot 应用程序中实现安全性?
- python - 如何将 sklearn 目标转换器(用于输出变量)添加到 keras 神经网络管道?
- javascript - window.opener 的“关闭”属性