I'm attempting tkinter in python for the first time but the Button
command creates an error
from tkinter import *
fenetre=Tk()
label=Label(fenetre,text="Hello World ! ")
label.pack()
fenetre.mainloop()
bouton=Button(fenetre,text="fermer", command=fenetre.quit)
boutoun.pack()
It should create a window with a button but I just receive the error message:
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
<ipython-input-21-fd57f3be1272> in <module>
----> 1 bouton=Button(fenetre,text="Exit !", command=fenetre.quit)
2 boutoun.pack()
~\anaconda3\lib\tkinter\__init__.py in __init__(self, master, cnf, **kw)
2648 overrelief, state, width
2649 """
-> 2650 Widget.__init__(self, master, 'button', cnf, kw)
2651
2652 def flash(self):
~\anaconda3\lib\tkinter\__init__.py in __init__(self, master, widgetName, cnf, kw, extra)
2570 for k, v in classes:
2571 del cnf[k]
-> 2572 self.tk.call(
2573 (widgetName, self._w) extra self._options(cnf))
2574 for k, v in classes:
TclError: can't invoke "button" command: application has been destroyed```
There's some similar questions in the forum but unfortunately they do not work for me.
CodePudding user response:
The correct code is:
from tkinter import *
fenetre=Tk()
label=Label(fenetre,text="Hello World ! ")
label.pack()
bouton=Button(fenetre,text="fermer", command=fenetre.destroy) # HERE (1)
bouton.pack()
fenetre.mainloop() # HERE (2)
- Use
fenetre.destroy
instead offenetre.quit
- The main loop should be the last line to catch events (to be simple)