2016-11-15 1 views
0

I는 입력 필드와 버튼이있는 응용 프로그램이 있습니다파이썬 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 키 내가이 오류가 발생하면 버튼이 작동하지만, I를 누르려고 만 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

제 생각에 가장 좋은 해결책은 람다를 사용하지 않는 것입니다. 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())