【问题标题】:How to set function parameter with Button in Tkinter?如何在 Tkinter 中使用 Button 设置功能参数?
【发布时间】:2024-05-01 06:00:02
【问题描述】:

我想创建一个函数,它将从按钮单击中获取参数。 例如:

from Tkinter import *

def func(b):
    number = 2*b
    print number
    return

root=Tk()

# By clicking this button I want to set b = 1 and call func

b1 = Button(root,...)
b1.pack()

# By clicking this button I want to set b = 2 and call func

b2 = Button(root,...)
b2.pack()

root.mainloop()

所以点击b1后,“number”应该是2,点击b2后,“number”应该是4。

我希望我能很好地解释我的问题。

感谢解答

安装末日

【问题讨论】:

    标签: python function button parameters tkinter


    【解决方案1】:

    这是一种方法

    from sys import stderr
    from Tkinter import *
    
    def func(b):
        number = 2*b
        stderr.write('number=%d\n'%number)
        return
    
    root=Tk()
    
    # By clicking this button I want to set b = 1 and call func
    
    b1 = Button(root,command=lambda : func(1))
    b1.pack()
    
    # By clicking this button I want to set b = 2 and call func
    
    b2 = Button(root,command=lambda : func(2))
    b2.pack()
    
    root.mainloop()
    

    【讨论】: