Python 如何在函数-tkinter中获取按钮文本?
如何获取函数中的特定按钮(触发函数)文本Python 如何在函数-tkinter中获取按钮文本?,python,tkinter,Python,Tkinter,如何获取函数中的特定按钮(触发函数)文本 from tkinter import * root = Tk() def clicked(): message = Label(root,text=f"You clicked {help?} button.") message.pack() button0= Button(root,text="Nice day for coding ain't it?",state=ACTIVE,padx=
from tkinter import *
root = Tk()
def clicked():
message = Label(root,text=f"You clicked {help?} button.")
message.pack()
button0= Button(root,text="Nice day for coding ain't it?",state=ACTIVE,padx=200,pady=5,command=clicked)
button1= Button(root,text="What does evil Morty want?",state=ACTIVE,padx=200,pady=5,command=clicked)
button2= Button(root,text="Microsoft Edge==Chrome downloader",state=ACTIVE,padx=200,pady=5,command=clicked)
button3= Button(root,text="Only real programmers use Mac",state=ACTIVE,padx=200,pady=5,command=clicked)
编辑:我想我已经找到了一个合适的解决方案
from tkinter import *
root = Tk()
def clicked(text):
print(text)
button0= Button(root,text="Suit up!",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button0.cget('text')))
button1= Button(root,text="Java should hide from kotlin",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button1.cget('text')))
button2= Button(root,text="Could it be more boring?",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button2.cget('text')))
button3= Button(root,text="Bazinga",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button3.cget('text')))
button0.pack()
button1.pack()
button2.pack()
button3.pack()
root.mainloop()
您可以通过使该命令成为一个带有参数的函数来实现,该参数具有您想要传递给它的默认值。下面是我的意思的一个例子。稍微棘手的部分是创建带有参数的
lambda
,该参数就是它所使用的小部件。在下面的代码中,这是通过将按钮
创建与配置其命令
选项分离来完成的,现在在它们全部存在后即可完成
from tkinter import *
root = Tk()
def clicked(btn):
btn_text = btn.cget('text')
message = Label(root, text=f'You clicked button "{btn_text}".')
message.pack()
buttons = [
Button(root, text="Nice day for coding ain't it?", state=ACTIVE, padx=200, pady=5),
Button(root, text="What does evil Morty want?", state=ACTIVE, padx=200, pady=5),
Button(root, text="Microsoft Edge==Chrome downloader", state=ACTIVE, padx=200, pady=5),
Button(root, text="Only real programmers use Mac", state=ACTIVE, padx=200, pady=5),
]
for button in buttons:
button.config(command=lambda btn=button: clicked(btn))
button.pack(fill=X)
root.mainloop()
非常感谢,先生。成功了。现在我来看看我应该在哪里改进这两个脚本以满足我的需要。g_odim_3:不客气。祝你好运。我强烈建议您阅读并尝试按照建议进行操作,以使您的代码更具可读性和可维护性。我会阅读它。martineau先生,您能看看我找到的解决方案吗?我编辑了我的问题。是的,这看起来像是使用
lambda
将参数传递给回调函数的另一种方式(除非您没有遵守PEP 8关于参数的指导原则)。