如何在 python Tkinter 中使用 lambda 将 Entry.get 设置为命令函数的参数

How to set Entry.get as an argument of a command function with lambda in python Tkinter

我的应用程序有一个输入字段和一个按钮:

    from subprocess import *
    from Tkinter import *


    def remoteFunc(hostname):
            command = 'mstsc -v {}'.format(hostname)
            runCommand = call(command, shell = True)
            return

    app = Tk()
    app.title('My App')
    app.geometry('200x50+200+50')

    remoteEntry = Entry(app)
    remoteEntry.grid()

    remoteCommand = lambda x: remoteFunc(remoteEntry.get()) #First Option
    remoteCommand = lambda: remoteFunc(remoteEntry.get()) #Second Option

    remoteButton = Button(app, text = 'Remote', command = remoteCommand)
    remoteButton.grid()

    app.bind('<Return>', remoteCommand)

    app.mainloop()

我希望当我将 ip/computer 名称插入输入字段时,它会将其作为参数发送给按钮命令,因此当我按下 Return 或按下按钮时它将使用 name/ip.

远程计算机

当我使用第一个选项(查看代码)执行此代码时,它仅在我按下 Return 键时起作用,如果我按下按钮,则会出现错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes exactly 1 argument (0 given)

如果我仅在尝试按下按钮时才尝试 remoteCommand 的第二个选项,它可以工作,但如果按下 Return 键,我会收到此错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes no arguments (1 given)

两者之间的唯一区别是 lambda 是否有参数。

我认为最好的解决方案是不使用 lambda。 IMO,应该避免使用 lambda,除非它确实是解决问题的最佳方法,例如当需要创建闭包时。

由于您希望从 return 键上的绑定调用相同的函数,并通过单击按钮,编写一个可选择接受事件的函数,然后简单地忽略它:

例如:

def runRemoteFunc(event=None):
    hostname = remoteEntry.get()
    remoteFunc(hostname)
...
remoteButton = Button(..., command = remoteFunc)
...
app.bind('<Return>', remoteCommand)

命令没有参数。事件处理程序获取一个事件作为参数。要让一个函数兼作两者,请使用默认参数。

def remote(event=None):
     remoteFunc(remoteEntry.get())