2016-11-15 5 views
0

私は、入力フィールドとボタンがあるアプリケーションがあります。PythonのTkinterではラムダとコマンド関数の引数としてEntry.getを設定する方法

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を挿入したとき、私はそれをしたいです/コンピュータ名を入力フィールドに入力すると、ボタンのコマンドにパラメータとして送信されるので、Returnキーを押すかボタンを押すと、その名前/ 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) 

:私は最初のオプションを使用してこのコードを実行すると

それは私がReturnキーを押し、と私はボタンを押した場合、これは誤りであるだけで動作します(コードを見て)私は、Returnキーを押しますが、私はこのエラーを取得する場合、ボタンのそれの仕事が、私を押ししようとした場合にのみremoteCommandの2番目のオプションは:ラムダ引数を取得するかどう

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) 

2の唯一の違いはあります。

答えて

1

私の意見では、ラムダを使用しないことが最良の解決策です。 IMOでは、ラムダは、クロージャを作成する必要がある場合など、実際に問題の最良の解決策でない限り、避けるべきです。

あなたは同じ関数がリターンキーを拘束から呼び出され、ボタンのクリックから、必要に応じてイベントを受け入れる関数を記述して、単にそれを無視することにしたいので:たとえば

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()) 
関連する問題