You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tkinter开发中如何在回调函数内获取触发事件的按钮text文本内容

Tkinter点击按钮获取触发事件按钮的text内容解决方案

可用实现方案

你自行编写的通过lambda传递参数的方案已经可以正确实现需求,原理如下:

  • cget('text')是Tkinter控件通用的属性读取方法,传入属性名即可获取对应属性值,这里用来读取按钮的text文本
  • 通过匿名函数lambda提前把对应按钮的文本值传入clicked回调函数,触发点击时就可以直接拿到对应按钮的内容

你写的可运行完整代码如下:

from tkinter import *
root = Tk()


def clicked(text):
    print(text)
    

button0= Button(root,text="准备出击!",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button0.cget('text')))
button1= Button(root,text="Java该躲着点Kotlin",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button1.cget('text')))
button2= Button(root,text="还能更无聊点吗?",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button2.cget('text')))
button3= Button(root,text="逗你玩",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button3.cget('text')))

button0.pack()
button1.pack()
button2.pack()
button3.pack()

root.mainloop() 

其他拓展实现方案

1. 批量创建按钮场景优化方案

如果按钮数量较多,不用逐个手动编写按钮实例和lambda参数,用循环批量生成即可,注意要给lambda设置默认参数固定当前值,避免闭包陷阱:

from tkinter import *
root = Tk()

def clicked(text):
    Label(root, text=f"你点击了按钮:{text}").pack()

# 提前定义所有按钮的text文本
btn_text_list = [
    "今天适合写代码不是吗?",
    "邪恶莫蒂想要什么?",
    "微软Edge=Chrome下载器",
    "只有真程序员用Mac"
]

for text in btn_text_list:
    btn = Button(root, text=text, state=ACTIVE, padx=200, pady=5)
    # 给lambda加默认参数,固定当前循环的text值
    btn.config(command=lambda current_text=btn.cget('text'): clicked(current_text))
    btn.pack()

root.mainloop()

2. 事件绑定方案

不用提前传参,通过绑定鼠标点击事件,直接从事件对象中获取触发事件的控件,再读取text属性,灵活性更高:

from tkinter import *
root = Tk()

def clicked(event):
    # event.widget就是触发本次点击事件的控件
    btn_text = event.widget.cget('text')
    Label(root, text=f"你点击了按钮:{btn_text}").pack()

button0= Button(root,text="今天适合写代码不是吗?",state=ACTIVE,padx=200,pady=5)
button1= Button(root,text="邪恶莫蒂想要什么?",state=ACTIVE,padx=200,pady=5)
button2= Button(root,text="微软Edge=Chrome下载器",state=ACTIVE,padx=200,pady=5)
button3= Button(root,text="只有真程序员用Mac",state=ACTIVE,padx=200,pady=5)

# 绑定鼠标左键点击事件触发回调函数
button0.bind("<Button-1>", clicked)
button1.bind("<Button-1>", clicked)
button2.bind("<Button-1>", clicked)
button3.bind("<Button-1>", clicked)

button0.pack()
button1.pack()
button2.pack()
button3.pack()

root.mainloop()

内容的提问来源于stack exchange,提问作者g_odim_3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 10:06:04