2016-11-15 1 views
0

J'ai une application qui a un champ d'entrée et un bouton:Comment définir Entry.get comme argument d'une fonction de commande avec lambda en 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() 

et je veux que quand j'insérer une adresse IP/nom de l'ordinateur dans le champ d'entrée, il sera envoyé en tant que paramètre à la commande du bouton, donc quand j'appuie sur Retour ou en appuyant sur le bouton, il va éloigner l'ordinateur avec ce nom/ip.

Quand j'exécute ce code avec la première option (regardez le code) il ne fonctionne que j'appuie sur la touche Retour, et si j'appuie sur le bouton c'est l'erreur:

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) 

Si je tente la deuxième option de remoteCommand que si je tente d'appuyer sur le bouton ce travail, mais je si appuyez sur la touche Retour i obtenir cette erreur:

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) 

la seule différence entre les deux est si lambda obtient un argument ou non.

Répondre

1

La meilleure solution à mon avis est de ne pas utiliser lambda. IMO, lambda devrait être évité à moins qu'il ne soit vraiment la meilleure solution à un problème, comme quand une fermeture doit être créée.

Puisque vous voulez la même fonction à appeler à partir d'un liant la clé de retour, et à partir du clic d'un bouton, écrire une fonction qui accepte éventuellement un événement, puis ignore simplement:

Par exemple :

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

Les commandes n'obtiennent pas d'arguments. Les gestionnaires d'événements obtiennent un événement en tant qu'argument. Pour qu'une fonction serve à la fois, utilisez un argument par défaut.

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