2015-11-08 2 views
1

Ceci est mon code:Pourquoi appeler entry.get() me donne "nom de commande invalide"?

def ask(what,why): 
    root=Tk() 
    root.title(why) 
    label=Label(root,text=what) 
    label.pack() 
    entry=Entry(root) 
    entry.pack() 
    button=Button(root,text='OK',command=root.destroy) 
    button.pack() 
    root.mainloop() 
    return entry.get() 

Et quand je l'appelle le code:

print(ask('Name:','Hello!')) 

je reçois:

Traceback (most recent call last): 
    File "C:\gui.py", line 16, in <module> 
    ask('Name:','Hello!') 
    File "C:\gui.py", line 15, in ask 
    return entry.get() 
    File "C:\Python34\lib\tkinter\__init__.py", line 2520, in get 
    return self.tk.call(self._w, 'get') 
_tkinter.TclError: invalid command name ".48148176" 

J'utilise Python sur 32 3.4.3 bits de Windows 7.

Répondre

3

Lorsque vous appuyez sur le bouton, l'application est détruite, le mainloop se termine, et vous essayez de renvoyer le contenu d'un widget Entry ... dans une application qui a été détruite. Vous devez enregistrer le contenu de entry avant de détruire l'application. Au lieu de vous frayer un chemin à travers cela, il vaudrait beaucoup mieux mettre en place une application Tkinter de la manière appropriée, par exemple avec une approche orientée objet.

class App: 
    # 'what' and 'why' should probably be fetched in a different way, suitable to the app 
    def __init__(self, parent, what, why): 
     self.parent = parent 
     self.parent.title(why) 
     self.label = Label(self.parent, text=what) 
     self.label.pack() 
     self.entry = Entry(self.parent) 
     self.entry.pack() 
     self.button = Button(parent, text='OK', command=self.use_entry) 
     self.button.pack() 
    def use_entry(self): 
     contents = self.entry.get() 
     # do stuff with contents 
     self.parent.destroy() # if you must 

root = Tk() 
app = App(root, what, why) 
root.mainloop()