首页 > 编程问答 >在 GUI 按钮构造函数中使用 lambda 函数作为命令选项

在 GUI 按钮构造函数中使用 lambda 函数作为命令选项

时间:2024-07-29 05:46:20浏览次数:8  
标签:python function user-interface lambda

我的问题是关于在用于为下面这个 Python 计算器创建 GUI 按钮的语法中使用 lambda 函数。

问题:我对如何编写 lambda 函数的理解如下 1) 中所示,那么它怎么可能按照 2) 中 GUI 按钮构造函数的命令选项中编写的方式编写它?

计算器的完整代码如下。 此 Python 计算器教程的视频可在此处找到:( https://www.youtube.com/watch?v=5UQZNHlaUVc&list=PLZPZq0r_RZOOkUQbat8LyQii36cJf2SWT&index=113 )

1)

add_one = lambda x : x + 1 add_one(2)

button1 = 按钮(框架,文本=1,高度=4,宽度=9,字体=35, 命令=lambda:button_press(1))

from tkinter import *



def button_press(num):                          

    global equation_text   

    equation_text = equation_text + str(num)  
                                       



    equation_label.set(equation_text)


def equals():

    global equation_text

    try:

        total = str(eval(equation_text))

        equation_label.set(total)

        equation_text = total   

    except SyntaxError:
        equation_label.set("syntax error")

        equation_text = ""           
                              

    except ZeroDivisionError:
        equation_label.set("arithmetic error")

        equation_text = ""


def clear():

    global equation_text

    equation_label.set("")

    equation_text = ""         


window = Tk()                       
window.title("Calculator program")                  
window.geometry("500x500")                      



equation_text = ""

equation_label = StringVar()


label = Label(window, textvariable=equation_label, font=('consolas',
20),bg='white',width=24,height=2)
label.pack()


frame = Frame(window)
frame.pack()

button1 = Button(frame,text=1,height=4,width=9,font=35,
                 command=lambda: button_press(1))
button1.grid(row=0,column=0)

button2 = Button(frame,text=2,height=4,width=9,font=35,
                 command=lambda: button_press(2))
button2.grid(row=0,column=1)

button3 = Button(frame,text=3,height=4,width=9,font=35,
                 command=lambda: button_press(3))
button3.grid(row=0,column=2)

button4 = Button(frame,text=4,height=4,width=9,font=35,
             command=lambda: button_press(4))
button4.grid(row=1,column=0)

button5 = Button(frame,text=5,height=4,width=9,font=35,
                 command=lambda: button_press(5))
button5.grid(row=1,column=1)

button6 = Button(frame,text=6,height=4,width=9,font=35,
                 command=lambda: button_press(6))
button6.grid(row=1,column=2)

button7 = Button(frame,text=7,height=4,width=9,font=35,
                 command=lambda: button_press(7))
button7.grid(row=2,column=0)

button8 = Button(frame,text=8,height=4,width=9,font=35,
                 command=lambda: button_press(8))
button8.grid(row=2,column=1)

button9 = Button(frame,text=9,height=4,width=9,font=35,
                 command=lambda: button_press(9))
button9.grid(row=2,column=2)

button0 = Button(frame,text=0,height=4,width=9,font=35,
                 command=lambda: button_press(0))
button0.grid(row=3,column=0)

plus = Button(frame,text='+',height=4,width=9,font=35,
                 command=lambda: button_press('+'))
plus.grid(row=0,column=3)

minus = Button(frame,text='-',height=4,width=9,font=35,
                 command=lambda: button_press('-'))
minus.grid(row=1,column=3)

multiply = Button(frame,text='*',height=4,width=9,font=35,
                 command=lambda: button_press('*'))
multiply.grid(row=2,column=3)

divide = Button(frame,text='/',height=4,width=9,font=35,
                 command=lambda: button_press('/'))
divide.grid(row=3, column=3)

equal = Button(frame,text='=',height=4,width=9,font=35,
                 command=equals)
equal.grid(row=3,column=2)

decimal = Button(frame,text='.',height=4,width=9,font=35,
                 command=lambda: button_press('.'))
decimal.grid(row=3,column=1)

clear = Button(window,text='clear',height=4,width=9,font=35,
                 command=clear)
clear.pack()





window.mainloop()

My understanding is it has to be written close to this for it to work, but can't explain why:         
command=lambda num: button_press(1)

你的理解是正确的!在 tkinter 按钮的 command 属性中使用 lambda 函数的方式与你所理解的方式略有不同,但本质上是一样的。

让我们来拆解一下:

  1. 你的理解 (lambda 表达式):

python add_one = lambda x : x + 1 add_one(2)

  • 这里,你定义了一个名为 add_one 的 lambda 函数,它接受一个参数 x 并返回 x + 1
  • 你调用 add_one(2) 时,lambda 函数立即执行,并将 2 传递给 x ,返回 3。

  • 按钮构造函数中的 lambda 函数:

python button1 = Button(frame, text=1, ..., command=lambda: button_press(1))

  • 这里, command 属性期望接收一个 函数 ,该函数将在按钮被点击时执行。
  • 你不能直接传递 button_press(1) ,因为这会 立即 调用函数,而不是在按钮点击时调用。
  • 因此,你使用 lambda: button_press(1) 创建一个 新的 lambda 函数。这个 lambda 函数没有参数,它做的事情就是在被调用时执行 button_press(1)

关键区别:

  • 在你的理解中,lambda 函数被立即调用。
  • 在按钮的 command 中,lambda 函数充当一个 中间层 ,它在按钮被点击时才被调用,并进而调用 button_press(1)

为什么需要 lambda 函数?

  • 你需要 lambda 函数来 延迟 button_press(1) 的执行,直到按钮被点击。
  • 如果没有 lambda 函数, button_press(1) 会在创建按钮时就被调用,而不是在按钮被点击时调用。

总结:

按钮构造函数中的 lambda 函数允许你将一个函数调用(例如 button_press(1) ) 延迟到按钮被点击时才执行。这在 GUI 编程中很常见,因为它允许你将数据(例如按钮的数字)与事件处理逻辑(例如 button_press 函数)关联起来。

标签:python,function,user-interface,lambda
From: 78804885

相关文章

  • 如何在Python中添加热键?
    我正在为游戏制作一个机器人,我想在按下热键时调用该函数。我已经尝试了一些解决方案,但效果不佳。这是我的代码:defstart():whileTrue:ifkeyboard.is_pressed('alt+s'):break...defmain():whileTrue:ifkeyboard.is_pr......
  • 在Python中解压文件
    我通读了zipfile文档,但不明白如何解压缩文件,只了解如何压缩文件。如何将zip文件的所有内容解压缩到同一目录中?importzipfilewithzipfile.ZipFile('your_zip_file.zip','r')aszip_ref:zip_ref.extractall('target_directory')将......
  • 如何在Python中从RSA公钥中提取N和E?
    我有一个RSA公钥,看起来像-----BEGINPUBLICKEY-----MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEAvm0WYXg6mJc5GOWJ+5jkhtbBOe0gyTlujRER++cvKOxbIdg8So3mV1eASEHxqSnp5lGa8R9Pyxz3iaZpBCBBvDB7Fbbe5koVTmt+K06o96ki1/4NbHGyRVL/x5fFiVuTVfmk+GZNakH5dXDq0fwvJyVmUtGYA......
  • Swagger、Docker、Python-Flask: : https://editor.swagger.io/ 生成服务器 python-fl
    在https://editor.swagger.io/上您可以粘贴一些json/yaml。我正在将此作为JSON进行测试(不要转换为YAML):{"swagger":"2.0","info":{"version":"1.0","title":"OurfirstgeneratedRES......
  • 使用 Matplotlib 的 Python 代码中出现意外的控制流
    Ubuntu22.04上的此Python3.12代码的行为符合预期,除非我按q或ESC键退出。代码如下:importnumpyasnp,matplotlib.pyplotaspltfrompathlibimportPathfromcollectionsimportnamedtuplefromskimage.ioimportimreadfrommatplotlib.widgets......
  • 参考 - Python 类型提示
    这是什么?这是与在Python中使用类型提示主题相关的问题和答案的集合。这个问题本身就是一个社区维基;欢迎大家参与维护。这是为什么?Python类型提示是一个不断增长的话题,因此许多(可能的)新问题已经被提出,其中许多甚至已经有了答案。该集合有助于查找现有内容。范......
  • 我的 Python 程序中解决 UVa 860 的运行时错误 - 熵文本分析器
    我正在尝试为UVa860编写一个解决方案,但是当我通过vJudge发送它时,它一直显示“运行时错误”。fromsysimportstdinimportmathdefmain():end_of_input=Falselambda_words=0dictionary={}text_entropy=0relative_entropy=0whilenotend_of_in......
  • Python进度条
    当我的脚本正在执行某些可能需要时间的任务时,如何使用进度条?例如,一个需要一些时间才能完成并在完成后返回True的函数。如何在函数执行期间显示进度条?请注意,我需要实时显示进度条,所以我不知道该怎么办。我需要thread为此吗?我不知道。现在在执行函数......
  • 此 Python 代码给出了超出时间限制的错误。由于其中使用的输入或输出方法而在其中传递
    N=int(input())L1=input()L=L1.split()s=set(L)d={}foreins:d[e]=L.count(e)print(d)max_value=max(d.values())print(max_value)L=list(d.values())print(L)res=L.count(max_value)print(res)/在提供正常输入时,它运行良好,但在提......
  • @staticmethod 在 Python 中意味着什么?
    我正在使用Python学习OOP。我想知道@staticmethod在OOP中到底做了什么。为什么我应该/不应该使用它?classCar:@staticmethoddefstart():print("carstarted")defstop():print("carstopped")当然,让我们来分解一下Pyth......