Doing sample tinker code does not work

copy and paste sample tinker and does not work
exit button does not exit

code below


import tkinter as tk

from tkinter import ttk

root window

root = tk.Tk()
root.geometry(‘300x200’)
root.resizable(False, False)
root.title(‘Button Demo’)

exit button

exit_button = ttk.Button(
root,
text=‘Exit’,
command=lambda: root.quit()
)

exit_button.pack(
ipadx=5,
ipady=5,
expand=True
)

root.mainloop()

Please wrap code in triple backticks to preserve the formatting:

```python
if True:
    print(''Hello world!')
```

When you’re creating the exit button, you have:

command=lambda: root.quit()

This will call root.quit() and pass its result to the function.

That should be:

command=lambda: root.quit

Actually, it can be as simple as:

 command = root.quit

No need for a lambda here.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

tried suggestion , still not exiting when click button
thank for reply

import tkinter as tk

from tkinter import ttk

# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Button Demo')

# exit button
exit_button = ttk.Button(
    root,
    text='Exit',
    command = root.quit
)

exit_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)

root.mainloop()

tried suggestion , still exit button does not work
thanks for reply

import tkinter as tk

from tkinter import ttk

# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Button Demo')

# exit button
exit_button = ttk.Button(
    root,
    text='Exit',
    command=lambda: root.quit
)

exit_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)

root.mainloop()

Forget what I said, It should be:

 command = root.quit

as Cameron said.

However, your original code does work.

Were you running it from a Python prompt?

If yes, then root.mainloop() will finish and the prompt will return, but the window will remain because the tkinter module still has a reference to it. That’s not a problem when you’re running a script because you’ll be quitting the Python interpreter just afterwards, but you can close that window by using root.destroy() instead.

am using IDLE (Python 3-11 64-bit)

run in visual studio code , and it worked there

wonder what the problem is with IDLE , though it is simpler to use than VS code

thanks

Same reason as I gave above: the Python interpreter is still running (IDLE is written in Python), and the tkinter module still has a reference to the window.