龙空技术网

python tkinter, 通过lambda表达式传递参数到按钮的点击事件函数

iwannacoding 146

前言:

当前朋友们对“pythontkinter按钮位置”大体比较关心,看官们都想要了解一些“pythontkinter按钮位置”的相关内容。那么小编同时在网上收集了一些对于“pythontkinter按钮位置””的相关内容,希望同学们能喜欢,各位老铁们快快来了解一下吧!

给tkinter的按钮添加点击事件处理函数,可以在创建按钮时将定义好的函数赋值给它的command属性,即

tk.Button(window, text='this is a button', command=clickFunc())

如果在点击按钮执行函数时还要传递参数,就要用到lambda了,写成以下形式

tk.Button(window, text='=', command=lambda: clickFunc(x, y, z))

写一个完整的小例子,来计算c = a + b

import tkinter as tkdef add(x, y, z):    x = int(x.get())    y = int(y.get())    z.set(str(x + y))def windows():    window = tk.Tk()    x = tk.StringVar()    a = tk.Entry(window, textvariable=x)    a.pack()    a.place(x=20, y=100, width=20)    x.set(1)    addLabel = tk.Label(window, text='+')    addLabel.pack()    addLabel.place(x=45, y=98)    y = tk.StringVar()    b = tk.Entry(window, textvariable=y)    b.pack()    b.place(x=60, y=100, width=20)    y.set(1)    z = tk.StringVar()    c = tk.Entry(window, textvariable=z)    c.pack()    c.place(x=120, y=100, width=20)    equalButton = tk.Button(window, text='=', command=lambda: add(x, y, z))    equalButton.pack()    equalButton.place(x=90, y=98)    window.mainloop()if __name__ == '__main__':    windows()

运行效果图

标签: #pythontkinter按钮位置 #tkinter 按钮 #python点击按钮运行一段程序