如何在 Tkinter 中将参数传递给 Button 命令?

2024-04-01

假设我有以下内容Button在 Python 中使用 Tkinter 制作:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

方法action当我按下按钮时调用,但是如果我想向该方法传递一些参数怎么办action?

我尝试过以下代码:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

这只是立即调用该方法,按下按钮不会执行任何操作。


See Python Argument Binders https://stackoverflow.com/questions/277922/python-argument-binders for standard techniques (not Tkinter-specific) for solving the problem. Working with callbacks in Tkinter (or other GUI frameworks) has some special considerations because the return value from the callback is useless.

If you try to create multiple Buttons in a loop, passing each one different arguments based on the loop counter, you may run into problems due to what is called late binding. Please see tkinter creating buttons in for loop passing command arguments https://stackoverflow.com/questions/10865116/ for details.


这可以使用lambda,像这样:

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

这是一种绑定参数的简单方法,无需显式包装方法或修改原始参数action.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Tkinter 中将参数传递给 Button 命令? 的相关文章

随机推荐