2016-11-15 48 views
0

我有,有一個輸入字段和一個按鈕的應用程序:如何設置Entry.get作爲命令的功能與拉姆達在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 /計算機名稱到輸入字段,它將它作爲參數發送到按鈕的命令,所以當我按回車或按下按鈕時,它將使用該名稱/ IP遠程計算機。

當我的第一個選項執行該代碼(看代碼),它只能我按下回車鍵,如果我按下按鈕,這是錯誤:

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的第二個選項只如果我嘗試按下按鈕它的工作,但我如果按返回鍵我得到這個錯誤:

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) 

兩者之間唯一的區別是,如果拉姆達得到一個說法或者不是。

回答

1

我認爲最好的解決方案是不使用lambda。 IMO,lambda應該被避免,除非它真的是問題的最佳解決方案,例如需要創建閉包時。

既然你想同樣的功能,從返回鍵的綁定調用,並從點擊按鈕,編寫選擇性地接受事件的函數,然後簡單地忽略它:

例如:

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

命令不會獲取參數。事件處理程序將事件作爲參數。要有一個函數作爲兩者,請使用默認參數。

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