0

I have tried to find a solution online but was not successful so I hope you can provide me a short and clear solution.

I want to execute the function change_value() after a button displayed on the window was pressed. After the execution, the window should be closed and the for-loop continued. I am not asking for a way to close the window immediately after pressing the button which is absolutely trivial.

Thanks!

root = tkinter.Tk()
variable = 0

def change_value(value):
    global variable
    variable = value

for iteration in range(0, 10):
    frame = tk.Toplevel()
    tk.Button(frame, text = 'Button 1', command = change_value(2)).pack()
    tk.Button(frame, text = 'Button 2', command = change_value(1)).pack()
    print(variable)
    ###Close window and continue with the for-loop after a button has been pressed
cspecial
  • 89
  • 9
  • Possible duplicate of [Function to close the window in Tkinter](https://stackoverflow.com/questions/8009176/function-to-close-the-window-in-tkinter) – Michael Kolber Jul 22 '19 at 20:04
  • It is not a duplicate since the thread you are referring to just explains the mechanic of closing the window after pressing the button *without* (the key part) executing a function which is associated with the button first. – cspecial Jul 22 '19 at 20:17
  • I don't understand the difference, sorry. Why can't you just put `root.destroy()` into your `change_value()` function? – Michael Kolber Jul 22 '19 at 20:20
  • 1
    Also, FYI your code has a lot more issues going on. `variable` is not being properly reassigned within `change_value()`, the `tk.Button()` calls execute the functions right away instead of passing them as objects. – Michael Kolber Jul 22 '19 at 20:22
  • root is used in other functions as well which are not listed here. I just want to close the current window without the need of also destroying root. – cspecial Jul 22 '19 at 20:23
  • 1
    How about [`withdraw()`](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.withdraw-method)? – Michael Kolber Jul 22 '19 at 20:25
  • 1
    `command=` needs function's name without `()` and arguments - it is called "callback". If you have to assign function with arguments then you can use `lambda` - `command=lambda:change_value(2)` – furas Jul 22 '19 at 22:19
  • Thanks to @MichaelKolber and furas. You helped me out! – cspecial Jul 23 '19 at 09:31

0 Answers0