-1

I have two buttons Start and Stop and when I click on the start button, I want to go through a while, but when I want to stop it, the Tkinter window is blocked and I can't click on the Stop button because the whole window is blocked.

Below is my code:

s = 1
def Start():
   while(s==1):
      #do something
def Stop():
   global s
   s = 0

btn_Start= Button(root, text = 'Start',width=9, height=2, command = Start).place(x=2,y=2)
btn_Stop = Button(root, text = 'Stop',width=9, height=2, command = Stop).place(x=2,y=42)

Does anyone know how can I stop the while?

Edited:-------- still the same error

enter image description here

Paul Vio
  • 57
  • 1
  • 7
  • Read [While Loop Locks Application](https://stackoverflow.com/questions/28639228/python-while-loop-locks-application) – stovfl Dec 26 '19 at 11:15

1 Answers1

1

If you want to run the function simultaneously with active window, you have to connect it with threading method.

The threading method creates a thread which creates a separate execution of your program.

Here's Your Solution,

import tkinter
import threading
from tkinter import *

root = Tk()

s = 1

def Start():
    while(s==1):
        print(s)
        #do something


def thread():
    global t
    t = threading.Thread(target = Start)
    t.start()

def Stop():
   global s
   s = 0
   t.join()
   print("Stopped")

btn_Start= Button(root, text = 'Start',width=9, height=2, command = thread).place(x=2,y=2)
btn_Stop = Button(root, text = 'Stop',width=9, height=2, command = Stop).place(x=2,y=42)

In above program the Start() is assigned as thread.Hence, when Start button is pressed the commanded thread() will create a new thread by executing Start() function. When Stop() function will called, t.join() will include that thread to your Stop() function execution.

Here you can find threading module documentation, https://docs.python.org/3/library/threading.html#module-threading

Divyesh Mehta
  • 191
  • 1
  • 9
  • It didn't work. I have added a photo in my question to see what happens. Can you have a look, please? – Paul Vio Dec 26 '19 at 11:37
  • My fault, I forgot to change the command for btn_start. It's working – Paul Vio Dec 26 '19 at 11:43
  • One more problem, the while is not stopping. I think it didn't take the same 's' – Paul Vio Dec 26 '19 at 11:50
  • The 's' is defined as global variable.So, when each function is called it uses assigned value of 's'.If while loop doesn't stop, you can use boolean variables and if else condition inside a while loop – Divyesh Mehta Dec 26 '19 at 12:23