-1

I have a very strange problem. When I press stop, the code does not stop. see:

import tkinter as tk
x=tk.Tk()
stops=False
def stop():
    stops=True
    print("STOPPED")
tk.Button(x,command=stop,text="Stop").pack()
while not stops:
    print(stops)
    x.update()
    x.update_idletasks()

If I press stop, why does still it keep on printing? the stops variable is not edited in the while loop, so why doesn't it stop? I have also tried adding this to the end of the while loop:

if stops:
    break

But it still does not stop. Why?

YJiqdAdwTifMxGR
  • 123
  • 1
  • 11

2 Answers2

0

I think you need to globalise the variable "stops" to modify the variable.

def stop():
    global stops
    stops=True
    print("STOPPED")

Yeshwin Verma
  • 282
  • 3
  • 16
0

I am bit late but with complete explanation

Yes, using global keyword will solve this issue.

Why and How ?

Explanation: Global variables are the one that are defined and declared outside a function and we need to use them inside a function

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Now if you want to update this global variable via function you need to use keyword global which will update the global variable(i.e, stops)

import tkinter as tk

x=tk.Tk()
stops=False


def stop():
    global stops
    stops=True
    print("STOPPED")


tk.Button(x, command=stop, text="Stop").pack()

while not stops:
    print(stops)
    x.update()
    x.update_idletasks()
Shakeel
  • 1,869
  • 15
  • 23