Search code examples
pythonloopstkinterbuttonbreak

Cant break loop using button


I wanted make window which will reappear if closed but will only close if user presses a button. I tried so many times but cant make. Plz help.

from Tkinter import *
x='y'
while x!='break':
    def something(x):
        x='break'
    root=tkinter.Tk()
    button=tkinter.Button(root, text='Break', command=lambda:something(x))
    button.pack()
    root.mainloop()
print('done')

Solution

  • When you set x using x = "break", you set the local variable which means that the global variable x is still "y". So to solve your problem just make sure that you use the global variable for x. This is a simple example:

    import tkinter as tk
    
    
    def something():
        # Use the global variable for `loop_running`
        global loop_running
        loop_running = False
        # You might also want to add: root.destroy()
    
    loop_running = True
    
    while loop_running:
        root = tk.Tk()
        button = tk.Button(root, text="Break", command=something)
        button.pack()
        root.mainloop()
    
    print("Done")